Django休息框架 - PrimaryKeyRelatedField

时间:2014-06-21 23:15:43

标签: django django-rest-framework

我正在关注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"
            ]
        }
    ]
}

这是打印出片段的__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
            ]
        }
    ]
}

这会打印出两个片段的主键ID - 我不明白

变体3 - 注释也会产生

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

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

1 个答案:

答案 0 :(得分:4)

来自Serializer Docs

  

默认的ModelSerializer使用关键主键

如果您没有指定任何内容,PrimaryKeyRelatedField将在幕后使用,那么您的Variation 2就是预期的输出。

希望这有帮助。