【问题标题】:django-tastypie and many to many "through" relationshipsdjango-tastypie 和多对多“通过”关系
【发布时间】: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' 并且不允许使用默认值或空值。

【问题讨论】:

    标签: django rest tastypie


    【解决方案1】:

    你提到:

    我可能自己发现了错误。 ToManyField 应该指向成分而不是配方成分。我会看看这是否有效。

    虽然 [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。并将attribute kwargs 自定义为返回ThroughModel Queryset 的回调函数。

    更新(2014 年 4 月)

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

    【讨论】:

    • 请在此帖子中包含答案的要点。 Stack Overflow 在这里不是作为链接的存储库,而是作为答案的存储库。这也是一种非常不恰当的方式来宣传你的博客。
    • 链接目前似乎已失效
    • 链接仍然失效,我无法在任何地方找到缓存版本。
    • @JayTaylor,链接已更新。希望对你有帮助。顺便说一句,我不再使用 Tastypie,而是使用 DjangoRestFramework (DRF)。
    • 你能在这里发布一个例子吗?链接失效了
    【解决方案2】:

    我和你有同样的问题。为了解决这个问题,我只是从 API 中删除了 ToMany 字段(如在 RecipeResource 中)。这对我们有用,因为模型仍然有 manytomany 字段(只是没有 API),您仍然可以通过查询中间模型来查询关系。

    【讨论】:

    • 这并不能真正回答问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 2012-02-29
    • 2016-04-18
    • 2015-02-15
    • 2012-11-25
    • 1970-01-01
    相关资源
    最近更新 更多