use*_*719 10 django django-rest-framework
找到Django-REST框架文档,尽管它有多长,但对我来说仍然太过背景.
restore_object方法的attrs函数有什么作用?
instance.title = attrs.get('title', instance.title)
Run Code Online (Sandbox Code Playgroud)
第二个论点代表什么,以及我将如何在未来的文档中寻找这将意味着什么?
也不确定双星号是什么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)
Run Code Online (Sandbox Code Playgroud)
我稍微更新了文档,旨在使其更加清晰......
http://django-rest-framework.org/tutorial/1-serialization.html#creating-a-serializer-class
该方法现在读取...
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)
Run Code Online (Sandbox Code Playgroud)
该**attrs风格使用Python的标准关键字扩展.在这里看到一个很好的解释.
它最终会相当于 Snippet(title=attrs['title'], code=attrs['code'], ...)
希望有所帮助!
| 归档时间: |
|
| 查看次数: |
3039 次 |
| 最近记录: |