【问题标题】:Django-REST Serializing RelatedFieldDjango-REST 序列化相关字段
【发布时间】:2014-01-29 19:27:53
【问题描述】:

我正在尝试使用文档 (http://www.django-rest-framework.org/api-guide/relations) 中的 RelatedFields 序列化模型,但我不断收到 AttributeError。

错误:

AttributeError at /testapi/foo/
'Foo' object has no attribute 'bar1'

模型:

class Foo(models.Model):

    foo_id = models.AutoField(primary_key=True)
    name = models.TextField()
    zip_code = models.TextField()

class Bar(models.Model):

    user = models.OneToOneField(User)
    arbitrary_field1 = models.ForeignKey(Foo, related_name='bar1')
    arbitrary_field2 = models.ForeignKey(Foo, related_name='bar2')

序列化器:

class FooSerializer(serializers.ModelSerializer):

    bar1 = serializers.RelatedField()
    bar2 = serializers.RelatedField()

    class Meta:

        model = Foo
        fields = (
                  'foo_id',
                  'name',
                  'zip_code',
                  'bar1',
                  'bar2',
                  )

【问题讨论】:

    标签: django serialization django-models django-rest-framework


    【解决方案1】:

    我可能对这个答案完全错误,因为我现在没有设置测试环境,但我会尽力而为。

    好的,在测试环境中尝试过,下面的解决方案对我有用。

    我不认为在这种情况下需要相关字段,因为您正在为两个任意字段指定相关名称,您只需要在字段元组中引用相关名称,而不是在序列化程序中使用 RelateField 指定它们。

    所以你可能会接受这个:

    class FooSerializer(serializers.ModelSerializer):
        class Meta:
            model = Foo
            fields = (
                      'foo_id',
                      'name',
                      'zip_code',
                      'bar1',
                      'bar2',
                      )
    

    这将返回类似这样的序列化数据:

    {
        ....
        "bar1": [
            1, 
            2, 
            3, 
            4
        ],
        "bar2": [
            1,
            2,
            3
        ]
        ....
    }
    

    只是一个旁注,但如果您不想要只是关系的 pk,您可以尝试将 Foo 序列化程序的 Meta 类中的深度变量设置为 1 或您想要的任何数字,例如来自文档http://www.django-rest-framework.org/api-guide/serializers#specifying-nested-serialization.

    或者,如果您想要更自定义的关系表示,您可以为 Bar 模型创建一个序列化程序,其中包含您想要包含或排除的任何字段,并在 Foo 序列化程序中使用该序列化程序,就像文档中的这个示例一样http://www.django-rest-framework.org/api-guide/relations#example.

    编辑:

    这是关于反向关系的 DRF 文档http://www.django-rest-framework.org/api-guide/relations#reverse-relations

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多