from rest_framework import serializers
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
def restore_object(self, attrs, instance=None):
"""
Given a dictionary of deserialized field values, either update
an existing model instance, or create a new model instance.
"""
if instance is not None:
instance.email = attrs.get('email', instance.email)
instance.content = attrs.get('content', instance.content)
instance.created = attrs.get('created', instance.created)
return instance
return Comment(**attrs)
比如,这其中的attrs是?
迷茫2017-04-17 13:45:30
這是python的參數列表,兩個星號是可變參數。 restore_object
接收到的attrs
參數是dict型,傳遞到Comment
函數的時候前面加上兩個星號轉成可變參數清單。
如
attrs = {'a':1, 'b':2}
Comment函數實際的呼叫會變成:
Comment(a=1, b=2)
參考:http://n3xtchen.github.io/n3xtchen/python/2014/08/08/python---args-and-kwargs/