Hello @kartik,
You can definitely do this using the validation on a field. The way you'd check if it's an update vs. creation is checking for self.instance in the validation function.
self.instance will hold the existing object and it's values, so you can then use it to compare against.
This should work for your purposes:
def validate_spouse(self, value):
if self.instance and value != self.instance.spouse:
raise serializers.ValidationError("Till death do us part!")
return value
Another way to do this is to override if the field is read_only if you're updating. This can be done in the __init__ of the serializer. Similar to the validator, you'd simply look for an instance and if there's data:
def __init__(self, *args, **kwargs):
# Check if we're updating.
updating = "instance" in kwargs and "data" in kwargs
# Make sure the original initialization is done first.
super().__init__(*args, **kwargs)
# If we're updating, make the spouse field read only.
if updating:
self.fields['spouse'].read_only = True
Hope it helps!!
Thank You!!