user798719
user798719

Reputation: 9869

Django REST-framework Serializer pk field?

What is the pk field in the Serializer class in Django-REST-framework?

I assume that it is the primary key, but is the name 'pk' a reserved term? How does the Serializer class know that is to be the primary key of the Snippet model?

I see no field in the Snippet model named 'pk'.

class SnippetSerializer(serializers.Serializer):
    pk = serializers.Field()  # Note: `Field` is an untyped read-only field.
    title = serializers.CharField(required=False,
                                  max_length=100)
    code = serializers.CharField(widget=widgets.Textarea,
                                 max_length=100000)
    linenos = serializers.BooleanField(required=False)
    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
                                       default='python')
    style = serializers.ChoiceField(choices=STYLE_CHOICES,
                                    default='friendly')

....class SnippetSeralizer continues

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES,
                                default='python',
                                max_length=100)
    style = models.CharField(choices=STYLE_CHOICES,
                             default='friendly',
                             max_length=100)

    class Meta:
        ordering = ('created',)

Upvotes: 7

Views: 9547

Answers (2)

Steve Wehba
Steve Wehba

Reputation: 181

And if you are using generic views in Django REST Framework, and you would like to use a different name for the pk field — say id, you can set lookup_field in your view to id.

Upvotes: 2

Brandon Taylor
Brandon Taylor

Reputation: 34553

pk is a property that lives on the base Model class in django.db.models:

class Model(object):
    ...
    pk = property(_get_pk_val, _set_pk_val)
    ...

which is used to identify the primary key for the model. I haven't used Django-REST, but they probably just map that to the field on the model.

Upvotes: 11

Related Questions