id字段在django休息框架序列化程序 [英] id field in django rest framework serializer
问题描述
我正在使用django休息框架,只需创建一个简单的序列化程序,如下所示:
I'm using django rest framework and just creating a simple serializer like this:
class PackageSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Package
fields = ('id','url', 'title','location')
但是我收到这个错误
KeyError at /cerberus/packages/
'id'
主键id作为我的序列化数据的一部分?感谢您的帮助!
How come I can't get the primary key 'id' as part of my serialized data? Thanks for helping!
推荐答案
HyperlinkedModelSerializer
不包含 id
。在2.2及更早版本中,您需要将其明确添加为字段...
HyperlinkedModelSerializer
doesn't include the id
by default. In 2.2 and earlier you'll need to add it explicitly as a field...
class PackageSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.Field()
class Meta:
model = Package
fields = ('id','url', 'title','location')
从2.3起,你可以简单地添加'id'到字段
选项...
From 2.3 onwards, you can simply add 'id' to the fields
option...
class PackageSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Package
fields = ('id','url', 'title','location')
从3.x起,您必须使用 ReadOnlyField()
而不是 Field()
如果你想添加它明确地不使用字段
选项...
From 3.x onwards, you must use ReadOnlyField()
instead of Field()
if you want to add it explicitly and not use the fields
option...
class PackageSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = Package
这篇关于id字段在django休息框架序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!