django tastypie和多对多“;透过「;关系
在Django和Tastypie中,我试图找出如何正确处理多对多“直通”关系,如以下所示: 以下是我的示例模型:django tastypie和多对多“;透过「;关系,django,rest,tastypie,Django,Rest,Tastypie,在Django和Tastypie中,我试图找出如何正确处理多对多“直通”关系,如以下所示: 以下是我的示例模型: class Ingredient(models.Model): name = models.CharField(max_length=100) description = models.TextField() class RecipeIngredients(models.Model): recipe = models.ForeignKey('Recipe')
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'
我试图将我的代码基于以下示例:
不幸的是,使用此代码,我得到了以下错误:
"error_message": "'Ingredient' object has no attribute 'recipe'"
有人知道这里发生了什么吗?或者如何在RecipeIngredEnterSource中包含成分名称?谢谢
编辑:
我可能自己发现了错误。ToManyField应针对成分,而不是接受成分。我看看这是否行得通
编辑:
新错误。。有什么想法吗?
对象“”的属性“title”为空,不允许使用默认值或空值。我遇到了与您相同的问题。为了解决这个问题,我只是从API中删除了ToMany字段(就像RecipeResource中一样)。这对我们有效,因为模型仍然有manytomy字段(只是没有API),您仍然可以通过查询中间模型来查询关系。您提到: 我可能自己发现了错误。ToManyField应针对成分,而不是接受成分。我看看这是否行得通 还有一个更好的方法,[Tastypie M2M]()(旧博客离线:) 简言之,我没有使用
ToManyField
作为配料,而是使用ToManyField
作为ThroughModel
。并将属性
kwargs自定义为通过模型Queryset返回的回调函数
更新(2014年4月)
这个答案很久以前就有了。不确定它是否仍然有用。请在这里的这篇文章中包含答案的要点。堆栈溢出在这里不是为了存储指向内容的链接,而是为了存储答案。这也是一种非常不合适的方式来推广你的博客。链接似乎在此时已失效链接仍然失效,我在任何地方都找不到缓存版本。@JayTaylor,链接已更新。希望这对你有帮助。顺便说一句,我不再使用Tastypie,而是使用DjangoRestFramework(DRF)。你能在这里发布一个例子吗??这个链接已经不起作用了,这并不能真正回答问题。