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() ?
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.
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.
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.
One solution is to use 2 queries.
You can use the reverse relationships to query all Group
s that an Item
in your items
points to.
groups = groups.objects.filter(item__in=items).distinct().values_list('name', flat=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With