Django how to filter based on ManyToManyField?
<p>Suppose I have the following Django classes:</p>

<p>in myclassa.py:</p>

<pre><code>class MyClassA(models.Model):
    name = models.CharField(max_length=254)

    def my_method(self):
        # WHAT GOES HERE?
</code></pre>

<p>in myclassb.py:</p>

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

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

<p>You may define it as:</p>

<pre><code>def my_method(self):
    return self.MyClassB_MyClassA.all()
</code></pre>

<p>Alternatively, you may also define it as:</p>

<pre><code>def my_method(self):
    return MyClassB.objects.filter(a=self)
</code></pre>

python django django-models django-queryset