如何基于一个对象共有的两个多重关系过滤查询集? [英] How can I filter a queryset based upon two manytomany relationships having one object in common?

查看:61
本文介绍了如何基于一个对象共有的两个多重关系过滤查询集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个动物查询集,并且我想编写一个查询来确定另一个模型上的多体动物字段是否具有至少一个与动物查询集相同的对象。

Suppose I have a queryset of animals and I want to write a query that determines if a manytomany field on another model has at least one object in common with the animals queryset. How can this be acheived?

farm_animals = Animals.objects.filter(name__in=["Dog", "Cow", "Horse"])

print farm_animals # [<Animal: Dog>, <Animal: Cow>, <Animal: Horse>]

# Returns all people who have at least one farm animal.
people_with_a_farm_animal = People.objects.filter(???)

这似乎应该容易做到,但我正在努力寻找一种有效的有效方法。预先感谢您的帮助。

This seems like it should be easy to do, but I'm struggling to find a good efficient way to do it. Thanks in advance for any help.

推荐答案

如danihp指出的,如果对象具有一个 owned_animals 字段,请尝试 people_with_a_farm_animal = People.objects.filter(own_animals__in = farm_animals).distinct()

As pointed out by danihp, if a People object has a owned_animals field try people_with_a_farm_animal = People.objects.filter( owned_animals__in=farm_animals).distinct().

这篇关于如何基于一个对象共有的两个多重关系过滤查询集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆