【发布时间】: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