【问题标题】:Filter django queryset to only include the results in the given list过滤 django 查询集以仅包含给定列表中的结果
【发布时间】:2012-01-09 12:35:26
【问题描述】:

所以我在 Django 中创建了一个“食谱”Web 应用程序,其中我有一个名为“用户的橱柜”的功能,用户可以在其中添加任何成分,他会看到一个称为“可制作食谱”的选项,应用程序会建议用户根据橱柜的成分可以制作哪些食谱。现在的问题是,如果我希望食谱包含橱柜中的任何成分,我可以执行“Recipe.objects.filter(ingredients__in=cabinet_ingredients)。如果我想过滤橱柜中的所有成分,我可以这样做:

qs = Recipe.objects.annotate(count=Count('ingredients'))\
                .filter(count=len(cabinet_ingredients))
for ingredient in cabinet_ingredients:
    qs = qs.filter(ingredients=ingredient)

但是,如果我想要橱柜成分的一个子集(这更有意义),那么食谱不应包含这些成分之外的任何东西,并且可以包含此列表中的任何东西。例如,给定 3 个橱柜成分,“foo”、“bar”、“baz”,我必须找到具有以下结果的食谱:

Recipes with 3 ingredients:
('foo', 'bar', 'baz')
Recipes with 2 ingredients:
('foo', 'bar'), 
('foo', 'baz'),
('bar', 'baz')
Recipes with single ingredient:
('foo')
('bar')
('baz')

这有什么线索吗?提前致谢。

【问题讨论】:

    标签: django


    【解决方案1】:

    假设您有一张配料表,您可以执行以下操作:

    # ingredients _not_ in the cabinet
    inner_qs = Ingredient.objects.exclude(name__in = cabinet_ingredients)
    # recipes that do not contain an ingredient that is _not_ in the cabinet
    qs = Recipe.objects.exclude(ingredients__in = inner_qs)
    

    【讨论】:

    【解决方案2】:

    @cha0site 的回答基本正确。但是,这将导致对数据库的两次查询,而只需要一次。请改用以下方法:

    from django.db.models import Q
    Recipe.objects.exclude(~Q(ingredients__name__in=cabinet_ingredients))
    

    【讨论】:

    • 嘿,根据文档,它会导致嵌套查询,可能会被数据库优化。我考虑过使用 Q 对象,但它不会和原来的Recipe.objects.filter(ingredients__in=cabinet_ingredients) 完全一样吗?还是我在逻辑中遗漏了什么?
    • Django 可能会在同一个请求中将内部查询与外部查询一起发送。如果是这种情况,那么任何一种方法都可能同样有效。但是,filter 实际上是不同的。对于您的版本和我的版本,我们明确排除了不在该列表中的任何内容,而您评论中的 filter 将仅包括任何具有这些成分的内容,无论它们是否还有 1000 种不在该列表中的其他成分。跨度>
    • 我不知道为什么这种方法会产生与 cha0site 发布的不同的不良结果。
    • @ChrisPratt,我认为您的查询排除了橱柜中没有任何成分的所有食谱,留下了至少有一种橱柜成分和一些其他成分的食谱。
    • @Chris,我想我知道您的查询出了什么问题。我们都想做的是Recipe.objects.exclude(ingredients__name__notin=cabinet_ingredients),但Django 没有notin 运算符。所以你使用了~Q(...__in=...),但这与notin 的含义不同。 ~Q(...) 语法表示Q(...) 的补码,因此您将获得Q(...) 未选择的每一行。因此,exclude(~Q(...)) 取消成为 filter(Q(...))。
    猜你喜欢
    • 2013-04-20
    • 2018-04-28
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2020-09-14
    • 2016-08-13
    • 2011-10-13
    • 1970-01-01
    相关资源
    最近更新 更多