Reputation: 16450
I have a few fields on my serializer and I have overridden the validate
method on serializer to do some object-level validation.
The problem is after validation, I need to edit the final data before passing it to create function. Currently, I'm doing this:
class MySerializer(serializers.ModelSerializer):
def validate(self, attrs):
# Some lengthy validation with attrs['a'] and attrs['b'] and attrs['c']
# if validated
attrs['a'] = updated_a
attrs['b'] = updated_b
attrs['c'] = updated_c
return attrs
Update has to be done after the validation. I was wondering if there is a better way to handle this.
I could subclass the Field
and provide custom to_internal
and to_representation
but I don't know how to do validation beforehand.
Upvotes: 3
Views: 4040
Reputation: 15484
validate
method is not the best place for this. Especially when now in DRF3 you have create
method available for you.
def create(self, validated_data):
data = validated_data.copy()
data['a'] = 'updated value'
return super(MySerializer, self).create(**data)
Upvotes: 8