我正在尝试使用 Tastypie 在 API 中关联两个资源(模型),但出现错误。
我遵循了django 教程并使用了:
模型.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 答案在 Poll 和 Choice 之间创建一个链接,并编写了以下代码:
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 还是需要更改我的原始模型?