我正在尝试将 Django 和 Django REST Framework 与 MongoEngine 一起使用,但它似乎对我不起作用。我不知道哪里出了问题……也许有人可以帮助我。这是代码:
模型.py
from mongoengine import *
class Lady(Document):
firstname = StringField()
lastname = StringField()
序列化程序.py
from rest_framework import serializers
from mongoengine import *
class LadySerializer(serializers.Serializer):
firstname = serializers.CharField(max_length=50)
lastname = serializers.CharField(max_length=50)
def restore_object(self,attrs,instance=None):
if instance:
instance.firstname = attrs.get('firstname', instance.firstname)
instance.lastname = attrs.get('lastname', instance.lastname)
return instance
return Lady(**attrs)
现在我使用交互式控制台测试序列化是否有效。我执行以下命令。
from core.models import *
from core.serializers import *
tiger = Lady(firstname='Tiger', lastname="Lily")
serial = LadySerializer(tiger)
serial.data
我得到的是:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/evermean/Code/django/env/pourl/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 499, in data
self._data = [self.to_native(item) for item in obj]
File "/home/evermean/Code/django/env/pourl/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 306, in to_native
value = field.field_to_native(obj, field_name)
File "/home/evermean/Code/django/env/pourl/local/lib/python2.7/site-packages/rest_framework/fields.py", line 164, in field_to_native
value = get_component(value, component)
File "/home/evermean/Code/django/env/pourl/local/lib/python2.7/site-packages/rest_framework/fields.py", line 56, in get_component
val = getattr(obj, attr_name)
AttributeError: 'str' object has no attribute 'firstname'
现在我真的不知道为什么会发生这种情况,因为 Lady 类中有一个 firstname 属性?我在这里想念什么?
谢谢...