gpt4 book ai didi

django - Tastypie 反向关系

转载 作者:行者123 更新时间:2023-12-04 10:26:57 26 4
gpt4 key购买 nike

我试图让我的 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/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com