Tastypie反向关系

roo*_*ler 7 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']
Run Code Online (Sandbox Code Playgroud)

当我点击我的api url时,我收到以下错误:

DocumentContainer' object has no attribute 'pod_events
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

谢谢.

Vic*_*ral 12

我在这里写了一篇博客文章: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()
Run Code Online (Sandbox Code Playgroud)

Models.py

class [top](models.Model):
    pass

class [bottom](models.Model):
    [top] = models.ForeignKey([top],related_name="[bottom]s")
Run Code Online (Sandbox Code Playgroud)

这个需要

  1. 在这种情况下,从子级到父级的models.ForeignKey关系
  2. 使用related_name
  3. 使用related_name作为属性的顶级资源定义.


sam*_*hen 1

更改您的行class DocumentContainerResource(...),从

pod_events = fields.ToManyField('portal.api.resources.DocumentEventResource', 
                                'pod_events')
Run Code Online (Sandbox Code Playgroud)

pod_events = fields.ToManyField('portal.api.resources.DocumentEventResource', 
                                'pod_event_set')
Run Code Online (Sandbox Code Playgroud)

在这种情况下,的后缀pod_event应该是_set,但根据具体情况,后缀可以是以下之一:

  • _set
  • _s
  • (无后缀)

如果每个事件最多只能与一个容器关联,还可以考虑更改:

pod = fields.ForeignKey(DocumentContainerResource, 'pod')
Run Code Online (Sandbox Code Playgroud)

到:

pod = fields.ToOneField(DocumentContainerResource, 'pod')
Run Code Online (Sandbox Code Playgroud)