找到 Django-REST 框架文档,尽管它很长,但对我来说背景太浅了。
restore_object 方法的 attrs 函数有什么作用?
instance.title = attrs.get('title', instance.title)
第二个参数代表什么,我将如何在文档中寻找这在未来意味着什么?
也不确定双星号的return Snippet(**attrs)
含义。这与 **keywArgs 不同?哪些参数被传递回反序列化的 Snippet 对象?
在文档的另一部分,我在 restore_object()instance.title = attrs['title']
中看到了我希望人们能够看到我的困惑。
谢谢你
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)