Can I update instance in one line without specifying all instance fields?
For example:
def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.address = validated_data.get('address', instance.address)
instance.save()
return instance
So imagine if there's many more fields next to name and address. Can I do something extracting kwargs from validated_data? Just like in create() method:
def create(self, validated_data):
return Person.objects.create(**validated_data)
It's not a one-liner but short enough (extracted from the drf sources):
def update(self, instance, validated_data):
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save()
return instance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With