Saqib Ali Saqib Ali - 3 months ago 20
Python Question

Django how to filter based on ManyToManyField?

Suppose I have the following Django classes:

in myclassa.py:

class MyClassA(models.Model):
name = models.CharField(max_length=254)

def my_method(self):
# WHAT GOES HERE?


in myclassb.py:

from myclassa import MyClassA
class MyClassB(models.Model):
name = models.CharField(max_length=254)
a = models.ManyToManyField(MyClassA, related_name="MyClassB_MyClassA")


Now suppose I have an instance
x
of
MyClassA
.
What do I put in
my_method()
such that it returns all the instances of
MyClassB
that contain
x
in their field
a
?

Answer

You may define it as:

def my_method(self):
    return self.MyClassB_MyClassA.all()

Alternatively, you may also define it as:

def my_method(self):
    return MyClassB.objects.filter(a=self)
Comments