Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework: how to make Id field required upon POST, i.e. non read-only field?

I've got a model, where I've overridden id as a CharField and primary key. Here's the model and its serializer:

class Tool(models.Model):
    id = models.CharField(max_length=10000, primary_key=True, default=uuid.uuid4, editable=False)
    description = models.TextField(null=True, blank=True)
    ...

class ToolSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Tool
        fields = (
            'id',
            'description',
            ...
        )

By default, Django REST Framework marks id field as read-only and doesn't require it upon POST requests. But I want it to be writable and require it upon POST. How do I achieve that?

like image 515
Boris Burkov Avatar asked May 12 '16 11:05

Boris Burkov


People also ask

How do you make a field optional in a serializer?

You could use a SerializerMethodField to either return the field value or None if the field doesn't exist, or you could not use serializers at all and simply write a view that returns the response directly. Update for REST framework 3.0 serializer. fields can be modified on an instantiated serializer.

What is write only field Django REST framework?

From DRF v3 onwards, setting a field as read-only or write-only can use serializer field core arguments mentioned as follows. write_only. Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.


1 Answers

I think, I found the answer in an unexpected place of DRF documentation:

http://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-update

I need to create an explicit id field in serializer like this:

class ToolSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.CharField()

    class Meta:
        model = Tool
        fields = (
            'id',
            'description',
            ...
        )

This will override the default id field, created as a read-only.

like image 192
Boris Burkov Avatar answered Oct 29 '22 03:10

Boris Burkov