In how many ways, can I get ManyToMany field data using Django ORM?

Question:

Let’s assume I have a model named A and B. In model B I have ManyToMany field to model A so in how many ways I can get data from model A using model B:

class A(models.Model):
    name= models.CharField(...)

class B(models.Model):
    a= models.ManyToManyField(A)
Asked By: Ankit Tiwari

||

Answers:

The two most straightforward ways is by accessing the a manager of the model object of B, so:

model_b_object.a.all()

another way to retrieve the related objects, is by filtering the B model, so:

A.objects.filter(b=model_b_object)

If you defined a through model, for example:

class A(models.Model):
    name= models.CharField(...)

class B(models.Model):
    a= models.ManyToManyField(
        A
        through='C'
    )

class C(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    b = models.ForeignKey(B, on_delete=models.CASCADE)

then you can also access this through:

A.models.objects.filter(c__b=model_b_object)

but this only will make the ORM call more complex, and less readable.

Answered By: Willem Van Onsem

Also, you can get data from model B using model A as shown below:

for obj in A.objects.all():
    print(obj.b_set.all())

And, the code above also works with Middle model defined between model A and model B and the results are the same:

class A(models.Model):
        name= models.CharField(...)

class B(models.Model):
    a = models.ManyToManyField(A, through="Middle")

class Middle(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    b = models.ForeignKey(B, on_delete=models.CASCADE)

    class Meta:
        unique_together = (('a', 'b'))

Buy me a coffee!!

Answered By: Kai – Kazuya Ito