Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 535
jul Avatar asked Feb 11 '13 20:02

jul


People also ask

How do I create a query in Django?

Creating objectsTo create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

How do I create a complex query in Django?

Your complex query require a subquery in the principle. Possible solutions are: A subquery written by 'extra' queryset method or raw SQL query. It is not DRY and it was unsupported by some db backends, e.g. by some versions of MySQL, however subqueries are by some limited way used since Django 1.1.

How do I create a join query in Django?

10. Join Queries. Join can be done with select_related method: Django defines this function as Returns a QuerySet that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query.


1 Answers

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.

like image 80
jpic Avatar answered Sep 23 '22 06:09

jpic