【问题标题】:Django rest framework - PrimaryKeyRelatedFieldDjango 休息框架 - PrimaryKeyRelatedField
【发布时间】:2014-06-21 23:15:43
【问题描述】:

我正在关注 Django REST 框架教程,现在我在这里: http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions#adding-endpoints-for-our-user-models

我的 UserSerializer 代码如下:

class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'snippets')

我想了解 PrimaryKeyRelatedField 到底是什么。为此,我正在按如下方式更改代码并刷新 URL http://127.0.0.1:8000/users/ 以查看不同的输出

变体 1

snippets = serializers.RelatedField(many=True, read_only=True)


{
    "count": 1, 
    "next": null, 
    "previous": null, 
    "results": [
        {
            "id": 1, 
            "username": "som", 
            "snippets": [
                "Snippet title = hello", 
                "Snippet title = New2"
            ]
        }
    ]
}

这是打印出 sn-ps 的 __unicode__() 值。我预料到了

变体 2 - 使用 PrimaryKeyRelatedField

snippets = serializers.PrimaryKeyRelatedField(many=True, read_only=True)


{
    "count": 1, 
    "next": null, 
    "previous": null, 
    "results": [
        {
            "id": 1, 
            "username": "som", 
            "snippets": [
                1, 
                2
            ]
        }
    ]
}

这打印出两个sn-ps的主键id - 我不明白

变体 3 - 注释掉也会产生

#snippets = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

{
    "count": 1, 
    "next": null, 
    "previous": null, 
    "results": [
        {
            "id": 1, 
            "username": "som", 
            "snippets": [
                1, 
                2
            ]
        }
    ]
}

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    来自Serializer Docs

    默认的 ModelSerializer 使用关系的主键

    如果您自己没有指定任何内容,PrimaryKeyRelatedField 将在后台使用,因此您的 Variation 2 是预期的输出。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2013-04-08
      • 2021-11-26
      • 1970-01-01
      • 2015-02-25
      • 2016-04-25
      • 2016-03-23
      • 2016-06-20
      相关资源
      最近更新 更多