Search code examples
pythondjangodjango-modelsmany-to-manydjango-orm

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


Let's assume I have two models named A and B. In model B, I have a ManyToMany field for model A, so how many ways can I get data from model A using model B?:

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

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

Solution

  • 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.