张江平的一夫一妻关系

2024-04-28 12:32:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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;

Tags: namefrommodelmodelsrecipelengthmaxclass
2条回答

实际上,使用filter似乎有更好的方法:

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

要打印每个配方及其成分:

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

相关问题 更多 >