Howto have some fields read_only only for updates

26 views
Skip to first unread message

Aron Podrigal

unread,
Nov 24, 2015, 9:37:52 PM11/24/15
to Django REST framework
Hi,

I would like to get some input on how to implement a serializer which would mark some fields read_only for either `create` or `update`. This is more a general problem which I think would be reasonable to have an option within the core. However in some cases it's just a matter of removing fields or marking fields read only or the opposite based on some state on the instance.

I thought of several ways to implement it.

  1. Use different serializers for create and update. 
    This solution is the simplest and in most cases the ideal one, as it is more explicit what the serializer is doing.
  2. Override init method and mark all fields as required.
  3. Add a Meta option eg. `non_updatable_fields` with a list of fields that is read_only for updates.
    More generic, can be implemented with a mixin, init method still needs be overridden by the mixin (which I don't like)
Option 3, using a mixin, can be implemented by overriding various methods, `__init__` or `get_fields` or any other method which will be called before the call to `is_valid`.
I don't like mixins which override methods that is have high chance of being overridden by another mixin, I hate super() calls.

Any ideas would be greatly appreciated.

Thanks.
Aron Podrigal
Reply all
Reply to author
Forward
0 new messages