MadDoctor5813
MadDoctor5813

Reputation: 281

Override update in Django Rest Framework without reimplementing the entire method?

So, I've been looking for a pattern or standard for this for a while, but I can't seem to find one.

Suppose I have some serializer:

WhateverSerializer(serializers.ModelSerializer):
    class Meta:
      model = Whatever
      fields = (
           'special',
           'field_1',
           'field_2'
           #a bunch more...
      )

And I want to have some special update behaviour just for the field special but no other fields. Is there a way to to override update without having to redo the entire update method like this?

def update(self, instance, validated_data):
    special_behaviour(instance.special)
    instance.field_1 = validated_data.get('field_1', instance.field_1)
    instance.field_2 = validated_data.get('field_2', instance.field_2)
    #a bunch more...

I've tried calling the ModelViewSet.update method, but it actually takes different parameters than the one you override in the viewset, and I'm not sure how exactly to pass the ones I have into that method.

Upvotes: 1

Views: 1846

Answers (1)

bdoubleu
bdoubleu

Reputation: 6107

Just remove the key from the dictionary of validated data, do your calculations, then use the super function to call the inherited update method which will .save() your changes.

def update(self, instance, validated_data):
    special = validated.data.pop('special')
    instance.special = perform_calc(special)
    return super().update(instance, validated_data)

Upvotes: 6

Related Questions