0

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.

4

1 回答 1

0

正如 danihp 所指出的,如果一个People对象有一个owned_animals字段 try people_with_a_farm_animal = People.objects.filter( owned_animals__in=farm_animals).distinct()

于 2013-06-02T20:08:27.297 回答