I ended up creating a custom base class for serializers with a custom
update method like the one you describe. It supports an additional
'immutable_fields' property on the Meta class:
from rest_framework.serializers import ModelSerializer
class BaseSerializer(ModelSerializer):
def update(self, instance, validated_data):
# Get the immutable fields from the Meta class
immutable = getattr(self.Meta, 'immutable_fields', [])
# Save all current values for immutable fields, to restore later
savedValues = {}
for field in immutable:
savedValues[field] = getattr(instance, field, None)
# Call the update method of the parent class to update all fields
obj = super().update(instance, validated_data)
# Restore immutable fields and save object
for field in savedValues:
if savedValues[field] is not None:
setattr(obj, field, savedValues[field])
obj.save()
return obj
On Thursday, October 27, 2016 at 4:45:20 PM UTC+2, Ed B wrote:
>
> I totally agree and I visited this group hoping to find and answer to this
> exact issue. Surely this is a fairly common use-case? In my case I want to
> be able to create a user with a username which should never be changed once
> created.
>
> On Thursday, October 6, 2016 at 4:53:52 PM UTC+2, Mikkel Mortensen wrote:
>>
>> I've several times found myself in the situation of writing separate
>> serializers for creating objects. it's in cases where I have a field that
>> is not quite `read_only`, not quite `write_only`. A better definition would
>> be `create_only`.
>>
>> An example (which is a bit lame) could be when i create a new `Person`.
>> The `PersonSerializer` has `read_only` fields `mother` and `father`, which
>> are other `Person`s that are serialized.
>>
>> What I usually do is to have `mother_id` and `father_id` fields as well,
>> which are `write_only`, to avoid having to supply the complex data
>> structures for whole `Person`s instead of just the `id`.
>>
>> But I don't want to be able to change those after creation, as it's
>> doesn't make (biological) sense to change parents once you're born. I could
>> check that these don't change in the `update` method of the
>> `PersonSerializer`, but that's tedious work.
>>
>> so I always end up writing a separate `NewPersonSerializer` with the
>> `mother_id` and `father_id` fields, which is used for creating new
>> `Person`s.
>>
>> So what i'm sort of missing is a `create_only` field -- a writable field
>> that is only available for creating objects. Has that ever been discussed?
>> Would it make sense to implement? Or is there a better way to achieve what
>> i'm trying to do in a single serializer, other than doing the previously
>> mentioned check in `update`?
>>
>
--
You received this message because you are subscribed to the Google Groups
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.