开发者

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

开发者 https://www.devze.com 2023-02-07 08:18 出处:网络
I have a twisty maze of interrelated Django models, with many-to-many fields describing the relationships.

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 Groups that an Item in your items points to.

groups = groups.objects.filter(item__in=items).distinct().values_list('name', flat=True)
0

精彩评论

暂无评论...
验证码 换一张
取 消