[Solved]-Django-REST framework restore_object attrs parameters


I’ve updated the documentation slightly in an aim to make that more clear…


The method now reads…

def restore_object(self, attrs, instance=None):
    Create or update a new snippet instance, given a dictionary
    of deserialized field values.

    Note that if we don't define this method, then deserializing
    data will simply return a dictionary of items.
    if instance:
        # Update existing instance
        instance.title = attrs.get('title', instance.title)
        instance.code = attrs.get('code', instance.code)
        instance.linenos = attrs.get('linenos', instance.linenos)
        instance.language = attrs.get('language', instance.language)
        instance.style = attrs.get('style', instance.style)
        return instance

    # Create new instance
    return Snippet(**attrs)

The **attrs style is using Python’s standard keyword expansion.
See here for a good explanation.

It’ll end up as the equivalent of Snippet(title=attrs['title'], code=attrs['code'], ...)

Hope that helps!


In DRF 3.0+ the restore_object method was removed. Now you can use two separate methods: .create and .update

def update(self, instance, validated_data): 
    instance.title = validated_data.get('title', instance.title) 
    instance.code = validated_data.get('code', instance.code) 
    instance.linenos = validated_data.get('linenos', instance.linenos)
    instance.language = validated_data.get('language', instance.language)         
    instance.style = validated_data.get('style', instance.style)  
    return instance 

def create(self, validated_data): 
    return Snippet.objects.create(**validated_data) 

Release notes: http://www.django-rest-framework.org/topics/3.0-announcement/

Leave a comment