Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 = items[0].groups.all().values_list('name', flat=True)

But for the whole set? Do I need to iterate through them all and do set().intersect() ?

like image 328
samurailawngnome Avatar asked Jan 28 '11 00:01

samurailawngnome


People also ask

How do you do a many-to-many relationship in Django?

To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.

What is many-to-many field in Django?

A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.

What does objects all () do in Django?

all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result. After calling all() on either object, you'll definitely have a QuerySet to work with.


1 Answers

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)
like image 159
Yuji 'Tomita' Tomita Avatar answered Sep 22 '22 16:09

Yuji 'Tomita' Tomita