2013-02-28 2 views
2

저는 그런 모델이 있습니다.django에는 모든 검색어가 포함되어 있습니다.

class Ingredient(models.Model): 
    name = models.CharField(max_length=128) 

class Recipe(models.Model): 
    name = models.CharField(max_length=128) 
    ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient') 

class RecipeIngredient(models.Model): 
    recipe = models.ForeignKey(Recipe) 
    ingredient = models.ForeignKey(Ingredient) 

모든 성분이 들어있는 요리법은 어떻게 찾을 수 있습니까?

다음은 예입니다.

>>> i1 = Ingredient(name="egg") 
>>> i1.save() 
>>> i2 = Ingredient(name="flour") 
>>> i2.save() 
>>> i3 = Ingredient(name="water") 
>>> i3.save() 
>>> i4 = Ingredient(name="milk") 
>>> i4.save() 
>>> i5 = Ingredient(name="sugar") 
>>> i5.save() 
>>> i6 = Ingredient(name="carrot") 
>>> i6.save() 
>>> i7 = Ingredient(name="wheat") 
>>> i7.save() 

>>> r1 = Recipe(name="omelet") 
>>> r1.save() 
>>> r1.ingredients.add(i1, i2, i3) 
>>> r2 = Recipe(name="icecream") 
>>> r2.save() 
>>> r2.ingredients.add(i3, i4, i5) 

>>> test = Recipe.objects.filter(ingredients__in=[i1.id, i2.id, i3.id, i4.id]) 
>>> test 
[<Recipe: omelet>, <Recipe: omelet>, <Recipe: omelet>, <Recipe: icecream>, <Recipe: icecream>] 

오믈렛 만 찾고 싶습니다. 만 오믈렛은 계란 (I1), 밀가루 (I2), 물 (I3)

감사

가 포함되어 있기 때문에

답변

0

어쩌면 그것을 함께 체인?

Recipe.objects.filter(ingredients=i1.id).filter(ingredients=i2.id).filter(ingredients=i3.id).filter(ingredients=i4.id) 
+0

>>> Recipe.objects.filter (성분 = i1.id) .filter (성분 = i2.id) .filter (성분 = i3.id) .filter (성분 = i4.id) [ ] – ecabuk

+0

아무 것도 반환하지 않습니다 ... – ecabuk

관련 문제