【问题标题】:How to filter queryset based on related models?如何根据相关模型过滤查询集?
【发布时间】:2016-01-08 09:53:30
【问题描述】:

我想获取基于杂货查询集的食谱查询集。 在我的 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 查询集中包含 HIGH PRIORITY 成分.grocery 的食谱。

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

我能想到的只是一个循环,我将在其中逐个检查食谱,但当食谱表包含大量数据时,它似乎效率很低。

有什么想法吗?

【问题讨论】:

    标签: python django


    【解决方案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())
    

    【讨论】:

    • 抱歉,我让自己不清楚,我编辑了我的问题。我不需要包含所有用户杂货的食谱,我需要杂货查询集中的所属成分的食谱。如果我有一个没有所属成分的食谱,它应该在食谱查询集中
    猜你喜欢
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2022-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多