我正在关注Django REST框架教程,并且目前在这里:http : //www.django-rest-framework.org/tutorial/4-authentication-and-permissions#adding-endpoints-for-our-user -楷模
我的UserSerializer代码如下所示:
class UserSerializer(serializers.ModelSerializer):
snippets = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = User
fields = ('id', 'username', 'snippets')
我试图确切地了解什么是PrimaryKeyRelatedField。为此,我正在按照以下方式更改代码并刷新URLhttp://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
]
}
]
}
默认的ModelSerializer使用主键建立关系
如果您未指定任何内容PrimaryKeyRelatedField
,那么您将自己在引擎盖下使用,因此您的版本2是预期的输出。
希望有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句