我目前正在做Django REST Framework tutorial我在测试时遇到了一些令我困惑的事情。
>>> snippet =Snippet(code='foo = "bar"\n')
>>> snippet.save()
>>> snippet = Snippet(code='print "hello, world"\n')
>>> snippet.save()
>>> serializer = SnippetSerializer(snippet)
>>> serializer.data
>>> {'style': 'friendly', 'code': u'print "hello, world"\n', 'language': 'python', 'title': u'', 'linenos': False, 'pk': 2}
特别是最后一行。我没有定义data
类或实例属性。 SnippetSerializer
类定义如下:
from django.forms import widgets
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
class SnippetSerializer(serializers.Serializer):
pk = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
code = serializers.CharField(style={'base_template': 'textarea.html'})
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
def create(self, validated_data):
"""
Create and return a new 'Snippet' instance, given the validated data.
"""
return Snippet.objects.create(**validated_data)
def update(self, instance, validated_data):
"""
Update and return an existing 'Snippet' instance, given the 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
我看到SnippetSerializer
类是serializers.Serializer
的亲戚(对吧?),但似乎也没有data
属性。它显然有效,并允许我访问所有SnippetSerializers
属性作为键值对数组。我无法在任何地方找到这方面的文档。 data
是python中的保留字吗?这是Django REST独有的东西吗?或者是否有一些我没有看到的遗产?
提前谢谢!