Mojimi Mojimi - 6 days ago 5
Python Question

Django get all ManyToMany relationships of an object

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 : http://pastebin.com/UQxwpbdN (My problem is with Pessoa and CCir)

Answer

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