我正在尝试将Django和Django REST框架与MongoEngine一起使用,但它似乎对我不起作用。我不知道哪里出了问题......也许有人可以帮助我。这是代码:
models.py
from mongoengine import *
class Lady(Document):
firstname = StringField()
lastname = StringField()
serializers.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属性?我在这里缺少什么?
谢谢...
答案 0 :(得分:11)
终于得到了解决方案。我需要明确设置 many = False 才能使其正常工作。所以这很好用:
from core.models import *
from core.serializers import *
tiger = Lady(firstname='Tiger', lastname="Lily")
serial = LadySerializer(tiger, many=False)
serial.data
和产量:
{'firstname': u'Tiger', 'lastname': u'Lily'}
您可以找到有关此问题的一些其他信息here。这个案例的有趣部分是以下帖子:
2.2版开始弃用隐式迭代行为。目前,您需要明确指定
many=False
以强制行为不迭代__iter__
样式对象。到2.4时,默认值将从None
切换为False
。
希望这会有所帮助......