问题
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