6👍
✅
I’ve updated the documentation slightly in an aim to make that more clear…
http://django-rest-framework.org/tutorial/1-serialization.html#creating-a-serializer-class
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!
4👍
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)
instance.save()
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/
- Call method once to set multiple fields in Django Rest Framework serializer
- What does a South datamigration do compared to a schemamigration?
- Language Localization of Khan Academy
- 'WinError 10013' running Django on Windows
- TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime'
Source:stackexchange.com