장고에서 일대일 관계를 평평하게합니다
문제
기본적인 일대일 관계를 가진 몇 가지 모델 클래스가 있습니다. 예를 들어, 책에는 많은 레시피가 있으며 각 레시피에는 많은 재료가 있습니다.
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)
제휴하지 않습니다 StackOverflow