如何根据相关模型过滤查询集?

时间:2015-10-10 14:59:43

标签: python django

我想根据杂货查询集获取配方的查询集。 在我的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)

我有一个用户选择的杂货查询集。

如何获取可与用户杂货一起烹饪的食谱查询集?这意味着我想要所有食品中包含HIGH PRIORITY ingredient.grocery包含在groceris queryset中。

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

我所能想到的只是一个循环,我会按食谱检查食谱,但是当食谱表包含大量数据时,它似乎效率低下。

任何想法?

1 个答案:

答案 0 :(得分: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())
相关问题