【问题标题】:How can I relate two models (django tutorial's Poll and Choice) in a Tastypie API如何在 Tastypie API 中关联两个模型(django 教程的投票和选择)
【发布时间】: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


    【解决方案1】:

    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()
    

    【讨论】:

      猜你喜欢
      • 2015-01-14
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 2014-02-01
      • 2017-02-24
      相关资源
      最近更新 更多