2015-10-10 80 views
0

我想獲得食譜基於雜貨查詢集的查詢集。 在我的models.py我有一個雜貨店模型如何根據相關模型過濾查詢集?

class Grocery(models.Model): 
    title = models.CharField(max_length=100) 
    picture = models.ImageField(upload_to='pictures/groceries', blank=True) 
    category = models.ForeignKey(Category, unique=False) 

我有一個配方模型:

class Recipe(models.Model): 
    title = models.CharField(max_length=100) 
    chef = models.ForeignKey(settings.AUTH_USER_MODEL, unique=False, related_name='chefs_recipe') 
    text = models.TextField() 
    picture = models.ImageField(upload_to='pictures/recipes/title-photos', blank=True) 

我有一個成分模型,它基本上是一個多對多的結表

class Ingredient(models.Model): 
    recipe = models.ForeignKey(Recipe, unique=False, related_name='recipeingredients') 
    grocery = models.ForeignKey(Grocery, unique=False) 
    quantity = models.DecimalField(max_digits=10, decimal_places=2) 
    PRIORITY = (
     ('high', 'inevitable'), 
     ('average', 'replaceble'), 
     ('low', 'flavoring') 
    ) 
    priority = models.CharField(max_length=20, choices=PRIORITY) 

我有一個由用戶選擇雜貨的查詢集。

我怎樣才能得到可以用用戶雜貨烹飪食譜的查詢集?這意味着我希望所有配方中的高優先級成分都包含在groceris queryset中。

def get_queryset(self): 
    groceries = Grocery.objets.filter(some_filter) 
    recipes = ? 

我能想到的是一個循環,我將通過配方檢查食譜,但它似乎主要是效率不高時,配方表將包含大量的數據。

有什麼想法嗎?

回答

1

我覺得這個解決您的問題:

def get_queryset(self): 
    groceries = Grocery.objets.filter(some_filter) 
    recipes = Recipe.objects.filter(pk__in=Ingredient.objects.filter(priority='high',grocery__in=groceries).values_list('recipe_id', flat=True).distinct()) 
+0

我appologize我自己清楚,我編輯我的問題。我不需要一個包含所有用戶雜貨的配方,我需要在食品雜貨查詢集中包含所屬材料的收件人。如果我有一個沒有所有成分的食譜,它應該在食譜queryset中 –