【发布时间】:2012-05-17 02:12:54
【问题描述】:
在 Django 和 Tastypie 中,我试图弄清楚如何正确处理多对多“通过”关系,就像在这里找到的那些:https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships
这是我的示例模型:
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 应该指向成分而不是配方成分。我会看看这是否有效。
编辑:
新错误..有什么想法吗? 对象 '' 有一个空属性 'title' 并且不允许使用默认值或空值。
【问题讨论】: