在Django和Tastypie我試圖找出如何妥善處理多對多「通過」的關係,就像那些在這裏找到:https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationshipsDjango的tastypie和多對多「通過」關係
這裏有我的樣本模型:
class Ingredient(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
class RecipeIngredients(models.Model):
recipe = models.ForeignKey('Recipe')
ingredient = models.ForeignKey('Ingredient')
weight = models.IntegerField(null = True, blank = True)
class Recipe(models.Model):
title = models.CharField(max_length=100)
ingredients = models.ManyToManyField(Ingredient, related_name='ingredients', through='RecipeIngredients', null = True, blank = True)
現在我api.py文件:
class IngredientResource(ModelResource):
ingredients = fields.ToOneField('RecipeResource', 'ingredients', full=True)
class Meta:
queryset = Ingredient.objects.all()
resource_name = "ingredients"
class RecipeIngredientResource(ModelResource):
ingredient = fields.ToOneField(IngredientResource, 'ingredients', full=True)
recipe = fields.ToOneField('RecipeResource', 'recipe', full=True)
class Meta:
queryset= RecipeIngredients.objects.all()
class RecipeResource(ModelResource):
ingredients = fields.ToManyField(RecipeIngredientResource, 'ingredients', full=True)
class Meta:
queryset = Recipe.objects.all()
resource_name = 'recipe'
我想在此基礎上例如我的代碼:http://pastebin.com/L7U5rKn9
不幸的是,有了這個代碼,我得到這個錯誤:
"error_message": "'Ingredient' object has no attribute 'recipe'"
有誰知道這裏發生了什麼?或者我可以如何在RecipeIngredientResource中包含成分的名稱?謝謝!
編輯:
我可能自己發現了錯誤。 ToManyField應該指向成分而不是配方成分。我會看看這是否能完成這項工作。
編輯:
新錯誤..任何想法? 對象''有一個空的屬性「標題」,不允許默認值或空值。
請在這裏列出答案的重要部分。堆棧溢出不是在這裏成爲一個東西的鏈接庫,而是成爲一個答案庫。這也是推廣博客的一種非常不恰當的方式。 –
Duh,好的,我將把答案複製到這裏......因爲帖子太長了...... – Yeo
鏈接似乎現在已經死了 – msc