Django Rest Framework, use `pk` instead of `id` by default with

Viewed 24

Say I have a model as follows:

from django.db import models

class Foo(models.Model):
    done = models.BooleanField(default=False, null=True)

And a serializer defined as follows:

from . import models

class FooSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Foo
        fields = '__all__'

FooSerializer(foo).data will be dict that has a id key, how can one make it have a pk key instead of id so that it matches the rest of my codebase (that use pk, since one-to-one models don't have an id field because they use a FK PK as their own PK.

2 Answers

Customize the serializer to allow a pk field instead of id taking in consideration that the serilaized data source is the model.id

from . import models

class FooSerializer(serializers.ModelSerializer):
    pk = serializers.ReadOnlyField(source='id')
    class Meta:
        model = models.Foo
        fields = ('pk', ....) # pk plus other fields

You can try this, extending the answer of @misraX .

from . import models

class FooSerializer(serializers.ModelSerializer):
    pk = serializers.ReadOnlyField(source='id')
    class Meta:
        model = models.Foo
        fields = '__all__'
        extra_fields = ['pk']
Related