所以我在Django中创建了一个'recipe'web应用程序,在那里我有一个名为“User's cabinet”的功能,用户可以在其中添加任何成分,提供一种称为“可制作食谱”的选项,其中应用程序将建议用户根据其内阁的成分能够制作哪些食谱。现在的问题是,如果我想让食谱中包含任何食材的成分,我可以做'Recipe.objects.filter(ingredients__in = cabinet_ingredients)。如果我想过滤所有机柜中的成分,我可以这样做:过滤django queryset只包含给定列表中的结果
qs = Recipe.objects.annotate(count=Count('ingredients'))\
.filter(count=len(cabinet_ingredients))
for ingredient in cabinet_ingredients:
qs = qs.filter(ingredients=ingredient)
但是如果我想机柜成分(这更有意义)的一个子集,使得配方不应该包含以外的任何东西这些成分可以包含任何东西在这个列表中。例如,给定3种内阁成分,“富”,“酒吧”,“巴兹”,我一定要找到,结果如下配方:
Recipes with 3 ingredients:
('foo', 'bar', 'baz')
Recipes with 2 ingredients:
('foo', 'bar'),
('foo', 'baz'),
('bar', 'baz')
Recipes with single ingredient:
('foo')
('bar')
('baz')
任何线索吗?提前致谢。
感谢一吨,作品像一个魅力:) – tejinderss 2012-01-10 06:49:06
太棒了!作为附录,您可能想阅读['in'字段查找文档](https://docs.djangoproject.com/en/1.3/ref/models/querysets/#in),尤其是_Performance_ _considerations_部分底部。 – cha0site 2012-01-10 10:42:25