Finding the Django-REST framework documentation to be, despite how lengthy it is, still too light on background for me.
What does the restore_object method's attrs function do?
instance.title = attrs.get('title', instance.title)
What does the second argument stand for, and how would I go about looking for what this would mean in the future in the docs?
Also not sure what the double asterisks in return Snippet(**attrs)
means. This is different from **keywArgs ? What arguments are being passed back to the deserialized Snippet object?
In another section of the docs, I see in restore_object() instance.title = attrs['title']
which I hope one might be able to see my confusion.
thank you
class SnippetSerializer(serializers.Serializer):
pk = serializers.Field() # Note: `Field` is an untyped read-only field.
title = serializers.CharField(required=False,
max_length=100)
code = serializers.CharField(widget=widgets.Textarea,
max_length=100000)
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES,
default='friendly')
def restore_object(self, attrs, instance=None):
"""
Create or update a new snippet instance.
"""
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)
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!
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