Jas*_*son 7 python django list flatten
我有一些基本的一对多关系的模型类.例如,一本书有很多食谱,每个食谱都有很多成分:
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)
Run Code Online (Sandbox Code Playgroud)
我想要一份特定书籍所有食谱中所有成分的清单.用Python表达这个的最好方法是什么?
如果我使用LINQ,我可能会写这样的东西:
var allIngredients = from recipe in book.Recipes
from ingredient in recipe.Ingredients
select ingredient;
Run Code Online (Sandbox Code Playgroud)
Jas*_*son 11
实际上,使用过滤器看起来有更好的方法:
my_book = Book.objects.get(pk=1)
all_ingredients = Ingredient.objects.filter(recipe__book=my_book)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5894 次 |
| 最近记录: |