Reputation: 3151
All my models have several ManyToMany relationships with other models and themselves, and they all have a "through" table
Let's say I have model A
, that has a ManyToManyField
with model B
and C
, let's also consider the field name is the same as the related model
And I have model D
that has a ManyToManyField with model A
.
Now, I want to get all objects related to an A
object of classes B
, C
and D
This is what I had tried :
a1 = A.objects.get(pk = 1)
#Get all B objects related to A
a1.b.all()
#Get all C objects related to A
a1.c.all()
#Get all D objects related to A but from D class because that's where the field is
#Raises error 'ManyToManyDescriptor' object has no attribute 'all'
D.a.all(pk=1)
Actual models can be found here (My problem is with Pessoa and CCir).
Upvotes: 1
Views: 5480
Reputation: 4267
You can use a.d_set.all()
in order to get reverse relation, or with the code you've provided:
obj = Pessoa.objects.get(pk=1) # get the object
obj.ccir_set.all()
Also you might consider providing related_name
for your m2m models
Upvotes: 6