如何定义用作自定义Django字段值的自定义类型的序列化

时间:2014-02-05 02:29:21

标签: django django-reversion

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

Reversion无法序列化我分配给自定义字段的值,声称它们不可序列化。如何为我的对象定义序列化方法?我不能只定义一个DjangoJSONEncoder子类(Django默认用于序列化的类),因为我无法控制调用其serialize方法的代码,因为它是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提出了一个模糊的建议。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

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

像这样

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

要进行反序列化,请确保您的to_python(self, value)工作正常