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;
4

2 回答 2

11

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

my_book = Book.objects.get(pk=1)
all_ingredients = Ingredient.objects.filter(recipe__book=my_book)
于 2008-11-17T02:00:37.927 回答
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)

文档

于 2008-11-17T01:52:19.533 回答