How can I filter a queryset based upon two manytomany relationships having one object in common?

爱⌒轻易说出口 提交于 2019-12-11 18:34:27

问题


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.


回答1:


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().



来源:https://stackoverflow.com/questions/16886801/how-can-i-filter-a-queryset-based-upon-two-manytomany-relationships-having-one-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!