Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

python - How to query directly the table created by Django for a ManyToMany relation?

I have a model MyModel2 with a ManyToManyField related to another model MyModel1.

How can I get the pairs mymodel1.id, mymodel2.id, as represented in the table Django creates for this relation? Do I have to do a raw SQL query on this table or is it possible through the object managers of this models?

class MyModel1(models.Model):
    name = models.CharField(max_length=50)
  

class MyModel2(models.Model):
    name = models.CharField(max_length=50)
    mymodel1 = models.ManyToManyField(MyModel1)
question from:https://stackoverflow.com/questions/14820579/how-to-query-directly-the-table-created-by-django-for-a-manytomany-relation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is the many to many field instance:

MyModel2.mymodel1

This is the intermediary table model:

MyModel2.mymodel1.through

This is the intermediary model manager:

MyModel2.mymodel1.through.objects

This returns a queryset for all intermediary models:

MyModel2.mymodel1.through.objects.all()

This part of django docs talk about through. You can make a through model yourself, else it is automatically generated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...