所以我在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