在Django rest框架中反序列化后获取类实例

时间:2015-01-28 18:21:20

标签: python django rest django-rest-framework

我正在尝试从给定的序列化中创建Userr对象。在Django REST Framework文档中,他们提到了必须返回实例的save()函数,但这不是正在发生的事情。

class Userr(object):
    def __init__(self, email, name):
        self.email = email
        self.name = name

class UserrSerializer(serializers.Serializer):
    email = serializers.EmailField()
    name = serializers.CharField()
    def create(self, validated_data):
        return Userr(**validated_data)

u_serializer = UserrSerializer(data={'email': bla.bla@ex.org', 'name': bla'})
print (u_serializer.is_valid())
user = u_serializer.save()

我希望使用类user的对象初始化Userr变量。相反,我看到以下错误:

Traceback (most recent call last):
  File "/Users/katkov/PycharmProjects/hbp-knowledge-graph/platform_venv/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/Users/katkov/PycharmProjects/hbp-knowledge-graph/hbp_knowledge_graph/ontology/tests/test_dataset_json_deserializer.py", line 73, in testSerializers
    u_serializer.save()
  File "/Users/katkov/PycharmProjects/hbp-knowledge-graph/platform_venv/lib/python2.7/site-packages/rest_framework/serializers.py", line 598, in save
    self.save_object(self.object, **kwargs)
  File "/Users/katkov/PycharmProjects/hbp-knowledge-graph/platform_venv/lib/python2.7/site-packages/rest_framework/serializers.py", line 580, in save_object
    obj.save(**kwargs)
AttributeError: 'dict' object has no attribute 'save'

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我得到了感谢mariodev。我使用rest_framework版本2.3并尝试在其上运行3.0代码。 对于3.0,该类应该如下:

class UserrSerializer(serializers.Serializer):
    email = serializers.EmailField()
    name = serializers.CharField()
    def restore_object(self, attrs, instance=None):
        if instance:
            # Update existing instance
            instance.email = attrs.get('email', instance.email)
            instance.email = attrs.get('name', instance.name)
            return instance
        return Userr(**attrs)