在Django中展平一对多的关系

时间:2021-11-10 06:51:16

I have a few model classes with basic one-to-many relationships. For example, a book has many recipes, and each recipe has many ingredients:

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

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)

I'd like a flat list of all ingredients in all recipes from a particular book. What's the best way to express this in Python?

我想要一份特定书籍所有食谱中所有成分的清单。用Python表达这个的最好方法是什么?

If I was using LINQ, I might write something like this:

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

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

2 个解决方案

#1


10  

Actually, it looks like there's a better approach using filter:

实际上,看起来使用过滤器的方法更好:

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

#2


2  

To print each recipe and its ingredients:

打印每个食谱及其成分:

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

And if you just want to get a list of all ingredient objects:

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

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.

文档。

#1


10  

Actually, it looks like there's a better approach using filter:

实际上,看起来使用过滤器的方法更好:

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

#2


2  

To print each recipe and its ingredients:

打印每个食谱及其成分:

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

And if you just want to get a list of all ingredient objects:

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

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.

文档。