我尝试使用Tastypie在一个API中关联两个资源(模型),但是我得到了一个错误。
我遵循了django tutorial并使用了:
models.py
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)我试图基于这个stackoverflow answer在投票和选择之间创建一个链接,并编写了以下代码:
api.py
class ChoiceResource(ModelResource):
poll = fields.ToOneField('contact.api.PollResource', attribute='poll', related_name='choice')
class Meta:
queryset = Choice.objects.all()
resource_name = 'choice'
class PollResource(ModelResource):
choice = fields.ToOneField(ChoiceResource, 'choice', related_name='poll', full=True)
class Meta:
queryset = Poll.objects.all()
resource_name = 'poll'当我转到: 127.0.0.1:8088/contact/api/v1/choice/?format=json
每件事都像它应该的那样工作。例如,我的其中一个选择链接到正确的投票:
{
"choice_text": "Nothing",
"id": 1,
"poll": "/contact/api/v1/poll/1/",
"resource_uri": "/contact/api/v1/choice/1/",
"votes": 6
}当我转到: 127.0.0.1:8088/contact/api/v1/poll/?format=json
我得到了:
{
"error": "The model '<Poll: What's up?>' has an empty attribute 'choice' and doesn't allow a null value."
}我是需要改用fields.ToManyField,还是需要更改我的原始模型?
发布于 2013-08-31 06:13:15
Tastypie recommends against creating reverse relationships (你在这里尝试做的关系是Choice -> Poll,你想要Poll -> Choice),但是如果你仍然想要,你可以。
摘自Tastypie文档:
与Django的ORM不同,Tastypie不会自动创建反向关系。这是因为涉及到大量的技术复杂性,以及可能无意中以不正确的方式向API的最终用户公开相关数据。
但是,仍然可以创建反向关系。不是传递给ToOneField或ToManyField一个类,而是传递一个表示所需类的完整路径的字符串。实现反向关系如下所示:
# myapp/api/resources.py
from tastypie import fields
from tastypie.resources import ModelResource
from myapp.models import Note, Comment
class NoteResource(ModelResource):
comments = fields.ToManyField('myapp.api.resources.CommentResource', 'comments')
class Meta:
queryset = Note.objects.all()
class CommentResource(ModelResource):
note = fields.ToOneField(NoteResource, 'notes')
class Meta:
queryset = Comment.objects.all()https://stackoverflow.com/questions/18541182
复制相似问题