如何基于一个对象共有的两个多重关系过滤查询集? [英] How can I filter a queryset based upon two manytomany relationships having one object in common?
问题描述
假设我有一个动物查询集,并且我想编写一个查询来确定另一个模型上的多体动物字段是否具有至少一个与动物查询集相同的对象。
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屋!