在Django中扁平化一对多关系

7

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

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;
2个回答

11

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

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

2
好吧,我想如果你想用简单的一行代码来实现它,你可以这样做。 ;) - Harley Holcombe

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)

文档


嗯,我并不是想打印这些成分,而是将它们收集到一个列表中。我想我可能错过了某个习语。 - Jason Anderson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接