Issue
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')
However I get this error:
KeyError at /cerberus/packages/
'id'
How come I can't get the primary key 'id' as part of my serialized data? Thanks for helping!
Solution
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')
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')
From 3.x (< 3.3) 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
Answered By - Tom Christie
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.