django-tastypie和许多"通过"关系

ben*_*nto 7 django rest tastypie

在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)
Run Code Online (Sandbox Code Playgroud)

现在我的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'
Run Code Online (Sandbox Code Playgroud)

我试图将我的代码基于这个例子:http://pastebin.com/L7U5rKn9

不幸的是,使用此代码我收到此错误:

"error_message": "'Ingredient' object has no attribute 'recipe'"
Run Code Online (Sandbox Code Playgroud)

有谁知道这里发生了什么?或者我如何在RecipeIngredientResource中包含成分的名称?谢谢!

编辑:

我可能自己发现了这个错误.ToManyField应该针对Ingredient而不是RecipeIngredient.我会看看这是否能完成这项工作.

编辑:

新错误..任何想法?对象''具有空属性'title',不允许使用default或null值.

Yeo*_*Yeo 3

您提到:

我自己可能已经发现了错误。ToManyField 应针对 Ingredient,而不是 RecipeIngredient。我看看这是否有效。

有一个更好的方法[Tastypie M2M] http://blog.eugene-yeo.in/django-tastypie-manytomany-through.html(旧博客已离线: https: //github.com/9gix/eugene- yeo.in/blob/master/content/web/django-tastiepie-m2m.rst )

简而言之,ToManyField我使用的不是成分,ToManyField而是ThroughModel。并将attributekwargs 自定义为返回ThroughModel查询集的回调函数。

更新(2014 年 4 月)

这个答案是很久以前就做出的。不确定它是否仍然有用。

  • 链接目前似乎已失效 (2认同)