質問

基本的な1対多の関係を持ついくつかのモデルクラスがあります。たとえば、本には多くのレシピがあり、各レシピには多くの材料があります:

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;
役に立ちましたか?

解決

実際には、フィルターを使用したより良いアプローチがあるようです:

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)

ドキュメント

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top