【问题标题】:Access to extra fields by directly querying the intermediate model通过直接查询中间模型访问额外的字段
【发布时间】:2018-07-09 17:26:01
【问题描述】:

我有以下问题: 我需要获取配方中某种成分的数量。

这是我的models.py:

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

    def __str__(self):
        return self.name

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

    def __str__(self):
        return self.name

class RecipeHasIngredients(models.Model):
    ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    quantity = models.IntegerField()

    def __str__(self):
        return str(self.recipe)

【问题讨论】:

    标签: django model


    【解决方案1】:

    有两种解决方案:

    1. 直接查询RecipeHasIngredients

      RecipeHasIngredients.objects.filter(recipe=recipe)

    2. 通过

      recipe_instance.ingredients.through.objects.all()

    在这两种情况下,您都会获得给定配方的 RecipeHasIngredients 实例列表

    【讨论】:

    • 使用您的第一个解决方案,我只得到了配方的名称,但我需要数量。使用您的第二个解决方案我得到错误:类型对象'RecipeHasIngredients'没有属性'all'。那么我怎样才能获得成分的数量呢?
    • 第一个解决方案返回一个列表print(type(value)) 以确保它不是字符串,也修复了第二个解决方案
    • 是的,我得到了RecipeHasIngredients 的列表,但没有得到数量。
    • 我通过使用解决了我的问题:RecipeHasIngredients.objects.filter(recipe=recipe).values_list('quantity', flat=True)
    猜你喜欢
    • 2012-05-16
    • 1970-01-01
    • 2020-06-12
    • 2011-12-21
    • 1970-01-01
    • 2017-03-09
    • 2019-08-27
    • 2019-02-19
    • 1970-01-01
    相关资源
    最近更新 更多