Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework update() with kwargs from validated_data

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)
like image 390
gagro Avatar asked Oct 11 '25 07:10

gagro


1 Answers

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
like image 173
Linovia Avatar answered Oct 16 '25 09:10

Linovia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!