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!
According to the Django docs:
Thus, if you need the
id
field in an update method, you must not declare it as read-only but use a read-write field instead:I just tweaked this to make it a little more pluggable by creating this class:
Then, just use that to make your serializer and you're on your way.
HyperlinkedModelSerializer
doesn't include theid
by default. In 2.2 and earlier you'll need to add it explicitly as a field...From 2.3 onwards, you can simply add 'id' to the
fields
option...From 3.x onwards, you must use
ReadOnlyField()
instead ofField()
if you want to add it explicitly and not use thefields
option...