Django REST ||蟒蛇?类属性作为键值对数组

时间:2015-03-06 14:01:59

标签: python django python-2.7 django-rest-framework

我目前正在做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独有的东西吗?或者是否有一些我没有看到的遗产?

提前谢谢!

1 个答案:

答案 0 :(得分:3)

data是BaseSerializer类的一个属性,Serializer继承该属性。请参阅the code