【问题标题】:How to define serialization for custom type used as value for custom Django field如何为自定义类型定义序列化,用作自定义 Django 字段的值
【发布时间】:2014-03-01 07:27:11
【问题描述】:

我创建了自己的自定义 models.TextField 子类,它将类作为其值并将这些值编码为数据库中给定类的 CODE 属性。到目前为止,所有这些都有效,但我想使用 Django-reversion,它会在每次进行更改时序列化模型并将模型保存在版本表中。我将其用于审核我的应用程序。

Reversion 无法序列化我分配给自定义字段的值,声称它们不可序列化。如何为我的对象定义序列化方法?我不能只定义一个 DjangoJSONEncoder 子类(Django 默认用来序列化的类),因为我无法控制调用其序列化方法的代码,因为它是 Django-reversion 的一部分。这是堆栈跟踪,最终在 Python 的默认 json 编码器中失败:

ERROR: Could not save initial version for AccessCircuitRTTicket 3.
Traceback (most recent call last):
  File "./manage.py", line 12, in <module>
    execute_from_command_line(sys.argv)
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/reversion/management/commands/createinitialrevisions.py", line 87, in handle
    self.create_initial_revisions(app, model_class, comment, batch_size, verbosity)
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/reversion/management/commands/createinitialrevisions.py", line 123, in create_initial_revisions
    default_revision_manager.save_revision((obj,), comment=comment)
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/reversion/revisions.py", line 430, in save_revision
    for obj in objects
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/reversion/revisions.py", line 430, in <genexpr>
    for obj in objects
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/reversion/revisions.py", line 108, in get_version_data
    "serialized_data": self.get_serialized_data(obj),
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/reversion/revisions.py", line 91, in get_serialized_data
    fields = list(self.get_fields_to_serialize()),
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/django/core/serializers/__init__.py", line 122, in serialize
    s.serialize(queryset, **options)
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/django/core/serializers/base.py", line 58, in serialize
    self.end_object(obj)
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/django/core/serializers/json.py", line 52, in end_object
    cls=DjangoJSONEncoder, **self.json_kwargs)
  File "/usr/lib/python2.7/json/__init__.py", line 181, in dump
    for chunk in iterable:
  File "/usr/lib/python2.7/json/encoder.py", line 427, in _iterencode
    for chunk in _iterencode_dict(o, _current_indent_level):
  File "/usr/lib/python2.7/json/encoder.py", line 401, in _iterencode_dict
    for chunk in chunks:
  File "/usr/lib/python2.7/json/encoder.py", line 401, in _iterencode_dict
    for chunk in chunks:
  File "/usr/lib/python2.7/json/encoder.py", line 435, in _iterencode
    o = _default(o)
  File "/home/sgalbraith/.python_virtualenvs/unleash/local/lib/python2.7/site-packages/django/core/serializers/json.py", line 104, in default
    return super(DjangoJSONEncoder, self).default(o)
  File "/usr/lib/python2.7/json/encoder.py", line 177, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <class 'console.broadband.enumerations.ProvisioningTicket'> is not JSON serializable

在 LazyEncoder 的定义及其前面的文本中,对答案 here 有一个模糊的建议。

【问题讨论】:

    标签: django django-reversion


    【解决方案1】:

    经过一天的努力,我想出了一个答案。我对它不是特别满意,因为它使责任远离我想要序列化的类型。一个更好的答案会很好!这就是我得到的...

    请注意,我拥有的 Django 自定义字段的值是类(即它们具有类型的类型)并且是 EnumMember 的子类,具有一个名为 CODE 的类成员,它给出了它们的字符串表示形式。

    我创建了以下模块 crm.serializers.json 并将设置中的 SERIALIZATION_MODULES 设置为

    SERIALIZATION_MODULES = {
        'json': 'crm.serializers.json',
    }
    

    crm.serializers.json 代码如下:

    # Avoid shadowing the standard library json module
    from __future__ import absolute_import
    
    from django.core.serializers.json import DjangoJSONEncoder, Serializer, \
        Deserializer as DjangoDeserializer
    from django.utils.encoding import force_text
    
    from crm.enum import EnumMember
    import json
    
    ####################################################################################################
    #
    #    Extension of Django serialization capability so that apps such as Django-reversion can deal
    #    with custom fields.
    #
    ####################################################################################################
    class Serializer(Serializer):
    
        # Override
        # This is a copy paste of the superclass method, but with cls=ExtendedJSONEncoder
        # instead of cls=DjangoJSONEncoder below
        def end_object(self, obj):
            # self._current has the field data
            indent = self.options.get("indent")
            if not self.first:
                self.stream.write(",")
                if not indent:
                    self.stream.write(" ")
            if indent:
                self.stream.write("\n")
            json.dump(self.get_dump_object(obj), self.stream,
                      cls=ExtendedJSONEncoder, **self.json_kwargs)
            self._current = None
            pass
    
    
    Deserializer = DjangoDeserializer
    
    
    class ExtendedJSONEncoder(DjangoJSONEncoder):
        """
        Provides default serialization for custom data types as well as default ones.
        """
        def default(self, obj):
            if type(obj) == type and issubclass(obj, EnumMember):
                return obj.CODE
            else:
                return super(ExtendedJSONEncoder, self).default(obj)
    

    【讨论】:

      【解决方案2】:

      不能肯定地说,因为我没有看到您的 TextField 子类,但是
      value_to_string(self, obj)
      在序列化框架中使用,你可以重写Field类的这个方法。

      喜欢这个

      def value_to_string(self, obj):
          return self.value_from_object(obj.CODE)
      

      对于反序列化,请确保您的 to_python(self, value) 工作正常

      【讨论】:

      • 我知道这是旧消息,但我遇到了同样的问题,所以提出了这个问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      相关资源
      最近更新 更多