장고에서 "recipe"웹 응용 프로그램을 만들었습니다. 장고에서는 사용자가 구성 요소를 추가 할 수있는 "사용자 캐비닛"이라는 기능이 있습니다. 'Makeable recipes'로 알려진 옵션이 제공됩니다.이 옵션에서는 사용자가 캐비닛의 재료를 사용하여 어떤 조리법을 만들 수 있는지 사용자에게 제안합니다. 이제 문제는 요리법에 캐비닛에있는 재료 중 하나를 포함하고 싶다면 '내가 할 수있는 요리법'. objects.info (캐비닛 _ 재료). 나는 캐비닛에 모든 재료를 필터링 할 경우에, 내가 할 수있는 :django queryset은 지정된 목록에 결과 만 포함합니다.
qs = Recipe.objects.annotate(count=Count('ingredients'))\
.filter(count=len(cabinet_ingredients))
for ingredient in cabinet_ingredients:
qs = qs.filter(ingredients=ingredient)
을하지만 난 캐비닛 성분 (어느 것이 더 의미)의 하위 집합을 원하는 경우 조리법 외부 아무것도 포함하지해야한다는 등 이 목록에는 무엇이든 들어있을 수 있습니다.
Recipes with 3 ingredients:
('foo', 'bar', 'baz')
Recipes with 2 ingredients:
('foo', 'bar'),
('foo', 'baz'),
('bar', 'baz')
Recipes with single ingredient:
('foo')
('bar')
('baz')
이에 대한 모든 단서 예를 들어 나는 다음과 같은 결과로 조리법을 찾기 위해, '갑', '바', '바즈'을 3 개 캐비닛 성분이 주어진? 미리 감사드립니다. cha0site의 대답은 대부분 정확 @
# 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)
감사합니다. 매력처럼 작동합니다. – tejinderss
굉장! 부록으로, [in in field lookup documentation] (https://docs.djangoproject.com/en/1.3/ref/models/querysets/#in), 특히 _Performance_ _considerations_ 섹션을 읽으십시오. 바닥. – cha0site