在Django和Tastypie我试图找出如何妥善处理多对多“通过”的关系,就像那些在这里找到: https://docs.djangoproject.com/en/dev/topics/db/models/#额外的字段上,多到多对多关系
这里是我的样本模型:
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应指向成分,而不是RecipeIngredient。 我会看到,如果这样做的工作。
编辑:
新的错误..任何想法? 对象“”有一个空的属性,“标题”,并且不允许缺省值或空值。