gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:27:11 25 4
gpt4 key购买 nike

我创建了自己的自定义 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

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

最佳答案

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

请注意,我拥有的 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)

关于django - 如何为用作自定义 Django 字段值的自定义类型定义序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21567534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com