django - Tastypie 反向关系

标签 django tastypie

我试图让我的 api 给我与tastypie 的反向关系数据。

我有两个模型,DocumentContainer 和 DocumentEvent,它们的关系如下:

DocumentContainer 有很多 DocumentEvents

这是我的代码:

class DocumentContainerResource(ModelResource):
    pod_events = fields.ToManyField('portal.api.resources.DocumentEventResource', 'pod_events')
    class Meta:
        queryset = DocumentContainer.objects.all()
        resource_name = 'pod'
        authorization = Authorization()
        allowed_methods = ['get']

    def dehydrate_doc(self, bundle):
        return bundle.data['doc'] or ''

class DocumentEventResource(ModelResource):

    pod = fields.ForeignKey(DocumentContainerResource, 'pod')
    class Meta:
        queryset = DocumentEvent.objects.all()
        resource_name = 'pod_event'
        allowed_methods = ['get']

当我点击我的 api 网址时,我收到以下错误:
DocumentContainer' object has no attribute 'pod_events

任何人都可以帮忙吗?

谢谢。

最佳答案

我在这里写了一篇关于这个的博客条目:http://djangoandlove.blogspot.com/2012/11/tastypie-following-reverse-relationship.html .

这是基本公式:

API.py

class [top]Resource(ModelResource):
    [bottom]s = fields.ToManyField([bottom]Resource, '[bottom]s', full=True, null=True)
    class Meta:
        queryset = [top].objects.all()

class [bottom]Resource(ModelResource):
    class Meta:
        queryset = [bottom].objects.all()

模型.py
class [top](models.Model):
    pass

class [bottom](models.Model):
    [top] = models.ForeignKey([top],related_name="[bottom]s")

这个需要
  • 在这种情况下,从子级到父级的 models.ForeignKey 关系
  • 使用related_name
  • 使用 related_name 作为属性的顶级资源定义。
  • 关于django - Tastypie 反向关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13462644/

    相关文章:

    ios - 使用 Twitter 在 iPhone 中登录用户并将经过身份验证的用户保存到远程 Django 应用程序

    django - 自定义鹡鸰站点地图

    html - Django - 模板对象访问详细名称

    Django 网址设计

    python - 多维数组模型 Django

    python - 向后与 Django 中的代理模型建立多对多关系

    python - Django-tastypie : Any example on file upload in POST?

    jquery - Tastypie 不发送 cookie

    python - 如何确保我的 AJAX 请求来自 Python 中的同一服务器

    Django Activity Feed(Feedly 集成?)