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 d开发者_如何学JAVAo 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() ?
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)
精彩评论