【问题标题】:Flattening one-to-many relationship in Django在 Django 中扁平化一对多关系
【发布时间】:2010-09-22 14:57:19
【问题描述】:

我有几个具有基本一对多关系的模型类。例如,一本书有很多食谱,每个食谱都有很多成分:

class Book(models.Model):
    name = models.CharField(max_length=64)

class Recipe(models.Model):
    book = models.ForeignKey(Book)
    name = models.CharField(max_length=64)

class Ingredient(models.Model):
    text = models.CharField(max_length=128)
    recipe = models.ForeignKey(Recipe)

我想要一份包含某本书所有食谱中所有成分的平面列表。用 Python 表达这一点的最佳方式是什么?

如果我使用的是 LINQ,我可能会这样写:

var allIngredients = from recipe in book.Recipes
                     from ingredient in recipe.Ingredients
                     select ingredient;

【问题讨论】:

    标签: python django list flatten


    【解决方案1】:

    要打印每个食谱及其成分:

    mybook = Book.objects.get(name="Jason's Cookbook")
    for recipe in mybook.recipe_set.all():
        print recipe.name
        for ingredient in recipe.ingredients:
            print ingredient.text
    

    如果您只想获取所有成分对象的列表:

    mybook = Book.objects.get(name="Jason's Cookbook")
    ingredient_list = []
    for recipe in mybook.recipe_set.all():
        for ingredient in recipe.ingredients:
            ingredient_list.append(ingredient)
    

    Documentation.

    【讨论】:

    • 嗯,我并不是要打印成分,而是将它们收集到一个列表中。我在想象这里可能有一个我遗漏的成语。
    【解决方案2】:

    实际上,使用过滤器似乎有更好的方法:

    my_book = Book.objects.get(pk=1)
    all_ingredients = Ingredient.objects.filter(recipe__book=my_book)
    

    【讨论】:

    • 好吧,我想如果您想以简单的单行方式进行操作,您可以这样做。 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 2019-04-23
    • 2016-11-24
    相关资源
    最近更新 更多