0

我一直无法理解为什么在我更改属性后传递给 field_to_native() 的对象(obj)会从 Nonetype 更改为正确的对象...

这是原始问题:将序列化程序的模型实例拆分为 3 个不同的字段

stackoverflow 的 mariodev 帮助我解决了最初的问题,但是我们俩都无法弄清楚一个奇怪的错误:

这是似乎有问题的代码:

COORD = dict(x=0, y=1, z=2)
class CoordField(serializers.Field):
    def field_to_native(self, obj, field_name):
        #retrieve and split coords
        coor = obj.xyz.split('x')
        return int(coor[COORD[field_name]])

class NoteSerializer(serializers.ModelSerializer):
    owner = serializers.Field(source='owner.username')
    firstname = serializers.Field(source='owner.first_name')
    lastname = serializers.Field(source='owner.last_name')
    x = CoordField()
    y = CoordField()
    z = CoordField()


class Meta:
    model = Note
    fields = ('id','owner','firstname','lastname','text','color','time','x', 'y', 'z')

xyz 是模型注解中的一个实例。根据回溯,当我做 obj.xyz 时,obj = None。

奇怪的是,如果我执行 obj.color,则 obj 会正确返回(注意:someuser)

我不明白 obj 如何仅通过更改属性来更改。

我无法理解的是 JSON 数据 'x' 'y' 和 'z' 正在传递给视图,而我的 div 框获得了正确的左侧、顶部和 z-index CSS 数据。如果这有效,为什么我会收到错误消息?

如果有错误,为什么数据仍然通过?

style="left: 343px; top: 110px; z-index: 3;"

如您所见,x,y,z DID 通过了。

任何启蒙都会很棒!非常感谢!

这是文本视图中的回溯:

Traceback:
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  140.                     response = response.render()
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/django/template/response.py" in render
  105.             self.content = self.rendered_content
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/rest_framework/response.py" in rendered_content
  59.         ret = renderer.render(self.data, media_type, context)
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/rest_framework/renderers.py" in render
  582.         post_form = self.get_rendered_html_form(view, 'POST', request)
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/rest_framework/renderers.py" in get_rendered_html_form
  485.             data = serializer.data
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/rest_framework/serializers.py" in data
  510.                 self._data = self.to_native(obj)
File "/home1/thecupno/python2.7/lib/python2.7/site-packages/rest_framework/serializers.py" in to_native
  309.             value = field.field_to_native(obj, field_name)
File "/home1/thecupno/django/notes/desk/serializers.py" in field_to_native
  10.         coor = obj.xyz#.split('x')      <-- I commented out .split, and the problem still persists.
Exception Type: AttributeError at /desk/restnote/
Exception Value: 'NoneType' object has no attribute 'xyz'
4

1 回答 1

3

我已经解决了我自己的问题。解决方案是确保序列化程序在对象为空时返回 None。

这是对顶部代码部分的更正:

COORD = dict(x=0, y=1, z=2)
class CoordField(serializers.Field):
def field_to_native(self, obj, field_name):
    if obj is None:
        return None
    else:
        #retrieve and split coords
        coor = obj.xyz.split('x')
        return int(coor[COORD[field_name]])

希望这对 Django 程序员有帮助!

于 2013-09-30T06:56:45.770 回答