【发布时间】:2013-08-30 20:43:08
【问题描述】:
我正在尝试使用 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 还是需要更改我的原始模型?
【问题讨论】:
标签: django api python-2.7 django-models tastypie