سؤال

ولدي بعض الطبقات نموذج مع العلاقات الأساسية واحدة لكثير. على سبيل المثال، وهو كتاب له صفات كثيرة، ولكل وصفة لديها العديد من المكونات:

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)

وأود الحصول على قائمة كاملة من جميع المكونات في جميع وصفات من كتاب معين. ما هي أفضل طريقة للتعبير عن هذا في بيثون؟

إذا كنت تستخدم 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