4

我正在尝试将 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 属性?我在这里想念什么?

谢谢...

4

1 回答 1

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'}

您可以在此处找到有关此问题的一些附加信息。这个案例的有趣部分是以下帖子:

2.2 版开始弃用隐式迭代行为。目前,您需要明确指定many=False以强制行为不迭代__iter__样式对象。到 2.4 时,默认值将从 切换NoneFalse

希望这可以帮助....

于 2013-06-22T19:00:23.657 回答