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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With