【问题标题】:Tastypie following a reverse relationship - not working to use related_name反向关系后的美味 - 无法使用相关名称
【发布时间】:2013-10-25 00:00:24
【问题描述】:

我有两个模型。

父母

class Parent(models.Model):
    ... code

孩子

class Child(models.Model):
    ... code
    parent = models.ForeignKey(Parent, related_name="parents")

还有一个 API

class ParentResource(ModelResource):
    children = fields.ToManyField("project.module.api.ChildResource", 'children', related_name='parents', null=True, blank=True, full=True)

    class Meta:
        queryset = Parent.objects.all()

class ChildResource(ModelResource):
    parent = fields.ForeignKey("project.module.api.ParentResource", 'parent')

    class Meta:
        queryset = Child.objects.all()

当我尝试访问父资源时,children 的数组为空。欢迎任何帮助澄清。

我查看了以前的答案 herehere 以及文档 here,但我仍然无法看到发生了什么。

谢谢

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    来自您的代码:

        parent = models.ForeignKey(Parent, related_name="parents")
    

    related_nameParent 模型上设置属性名称(在tastepie 资源上也是如此),默认为child_set,您现在将其设置为parents。这意味着Parent 模型p 将在名为parents 的属性处具有Child 对象的查询集,这显然是不对的。

    此外,父关系ChildResource 上的related_name 与相关模型上的属性不匹配。

    以下是每个应该可以正常工作的更正版本:

    型号

    class Parent(models.Model):
        ... code
    
    class Child(models.Model):
        ... code
        parent = models.ForeignKey(Parent, related_name="children")
    

    资源

    class ParentResource(ModelResource):
        children = fields.ToManyField("project.module.api.ChildResource", 'children', related_name='parent', null=True, blank=True, full=True)
    
        class Meta:
            queryset = Parent.objects.all()
    
    class ChildResource(ModelResource):
        parent = fields.ForeignKey("project.module.api.ParentResource", 'parent')
    
        class Meta:
            queryset = Child.objects.all()
    

    【讨论】:

    • 谢谢@lukeman。这对 Django 模型很有意义,但我不确定这是否适合 Django-Tastypie。我想我已经避免了足够长的时间,我可能需要切换到骨干关系而不是“有点”这样做。认识?
    • 在我看来,您的 Tastypie 资源看起来大部分都很好。 ParentResource 上的相关名称已关闭。我会用新的模型/资源更新我的答案,每个应该都能正常工作。
    • 另外,骨干关系是一个不相关的选择。这是让您的主干代码更加了解关系的一种巧妙方法(并且它涉及一些基本的缓存 IIRC),但是如果您的资源没有正确脱水,那既不是这里也不是那里。
    猜你喜欢
    • 2023-03-10
    • 2013-01-17
    • 2018-09-14
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多