Get all related many-to-many objects from a Django QuerySet?

Up vote 2 down vote favorite share g+ share fb share tw.

I have a twisty maze of interrelated Django models, with many-to-many fields describing the relationships. What's the cleanest way to get a list of unique members of a related model from a QuerySet? If I have a Item model with a groups ManyToMany pointing to the Groups model.

If I have a queryset of Items, of 'items', how do I get this: groups = items0.groups.all(). Values_list('name', flat=True) But for the whole set? Do I need to iterate through them all and do set().intersect()?

Python django many-to-many django-queryset link|improve this question asked Jan 28 '11 at 0:38samurailawngnome235110 67% accept rate.

One solution is to use 2 queries. You can use the reverse relationships to query all Groups that an Item in your items points to. Groups = groups.objects.

Filter(item__in=items).distinct(). Values_list('name', flat=True).

Sufficiently elegant. Thanks. – samurailawngnome Jan 28 '11 at 0:59 You may also find it useful to use flat=True as a parameter to values_list, which will return the result as a list of names, rather than a list of tuples of names.

– gorus Jan 30 '11 at 23:01 @gorus -- updated. I'm finding it funny I removed flat from the original post because I got it confused with distinct. – Yuji Tomita Jan 30 '11 at 23:31.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions


Thank You!
send