问题描述
在Django和Deliciouspie中,我试图弄清楚如何正确处理通过关系,例如在这里找到的:
In Django and Tastypie I'm attempting to figure out how to properly deal with Many to Many "through" relationships, like those found here: 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文件:
Now my api.py file:
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'
我试图基于以下示例创建代码:
I'm trying to base my code on this example: http://pastebin.com/L7U5rKn9
不幸的是,使用此代码,我收到此错误:
Unfortunately, with this code I get this error:
"error_message": "'Ingredient' object has no attribute 'recipe'"
有人知道这里发生了什么吗?或者如何在RecipeIngredientResource中包含成分名称?谢谢!
Does anyone know what's happening here? Or how I can include the name of the ingredient in the RecipeIngredientResource? Thanks!
编辑:
我可能自己也发现了错误。 ToManyField应该针对成分而不是RecipeIngredient。我会看看这是否起作用。
I may have found the error myself. ToManyField should be directed toward Ingredient and not RecipeIngredient. I'll see if this does the job.
编辑:
新错误..有什么想法吗?
对象的属性'title'为空,不允许使用默认值或null值。
New error.. any ideas?The object '' has an empty attribute 'title' and doesn't allow a default or null value.
推荐答案
您提到了:
虽然[Tastypie M2M] (旧博客离线:)
There's a better approach though [Tastypie M2M] (old blog is offline: https://github.com/9gix/eugene-yeo.in/blob/master/content/web/django-tastiepie-m2m.rst)
简而言之,我对配料使用了 ToManyField
而不是 ToManyField
ThroughModel
。并将自定义属性
kwargs设为返回 ThroughModel
查询集的回调函数。
In short summary, Instead of ToManyField
to Ingredients, I use ToManyField
toward the ThroughModel
. And customize the attribute
kwargs to be a callback function that return the ThroughModel
Queryset.
这个答案是很久以前做出的。不知道它是否仍然有用。
This answer is made long ago. Not sure if it is still useful.
这篇关于django-tastypie和许多到许多“直通”关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!