简体   繁体   English

Django:来自ManyToManyField的* all *值的queryset过滤器

[英]Django: queryset filter for *all* values from a ManyToManyField

Hi (sorry for my bad english :p) 嗨(抱歉我的英文不好:p)

Imagine these models : 想象一下这些模型:

class Fruit(models.Model):
    # ...

class Basket(models.Model):
    fruits = models.ManyToManyField(Fruit)

Now I would like to retrieve Basket instances related to all fruits. 现在我想检索与所有水果相关的篮子实例。 The problem is that the code bellow returns Basket instances related to any fruits : 问题是下面的代码返回与任何水果相关的Basket实例:

baskets = Basket.objects.filter(fruits__in=Fruit.objects.all())

# This doesn't work:
baskets = Basket.objects.filter(fruits=Fruit.objects.all())

Any solution do resolve this problem ? 任何解决方案都解决了这个问题

Thank you very much. 非常感谢你。 :) :)

I don't have a dataset handy to test this, but I think it should work: 我没有一个数据集方便测试这个,但我认为它应该工作:

Basket.objects.annotate(num_fruits=Count('fruits')).filter(num_fruits=len(Fruit.objects.all()))

It annotates every basket object with the count of related fruits and filters out those baskets that have a fruit count that equals the total amount of fruits. 它用相关水果的数量来注释每个篮子对象,并筛选出那些水果数量等于水果总量的篮子。

Note: you need Django 1.1 for this to work. 注意:你需要Django 1.1才能工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM