0

我正在尝试使用 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 还是需要更改我的原始模型?

4

1 回答 1

0

Tastypie 建议不要创建反向关系(你在这里尝试做的关系是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()
于 2013-08-30T22:13:15.173 回答