【问题标题】:Tastypie Reverse Relation美味的反向关系
【发布时间】:2023-03-10 18:25:01
【问题描述】:

我正在尝试让我的 api 为我提供与美味派的反向关系数据。

我有两个模型,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 url 时,我收到以下错误:

DocumentContainer' object has no attribute 'pod_events

谁能帮忙?

谢谢。

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    我在这里写了一篇关于此的博客文章: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")
    

    需要

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

    【讨论】:

    【解决方案2】:

    class DocumentContainerResource(...) 中更改您的线路,从

    pod_events = fields.ToManyField('portal.api.resources.DocumentEventResource', 
                                    'pod_events')
    

    pod_events = fields.ToManyField('portal.api.resources.DocumentEventResource', 
                                    'pod_event_set')
    

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

    • _set
    • _s
    • (无后缀)

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

    pod = fields.ForeignKey(DocumentContainerResource, 'pod')
    

    到:

    pod = fields.ToOneField(DocumentContainerResource, 'pod')
    

    【讨论】:

    • 嗯,即使在更改之后,它对我也不起作用。现在它说“'DocumentContainer'对象没有属性'pod_event_set'”
    • @rookieRailer 你介意从你的models.py中发布相关的sn-ps吗?
    • ForeignKey 是 ToOneField 的别名。
    猜你喜欢
    • 2013-01-17
    • 1970-01-01
    • 2018-09-14
    • 2016-05-08
    • 2021-05-17
    • 2018-07-05
    • 2012-04-19
    • 1970-01-01
    • 2014-05-27
    相关资源
    最近更新 更多