- 我有两个类:Website 和 WordpressWebsite。
- WordpressWebsite 子类网站。
当 WordpressWebsite 的一个实例被编码成 JSON 时,只有 WordpressWebsite 的属性存在(而不是 Website 的任何属性)。
我的目标是编写一个自定义编码器,它将 Wordpress 网站编码为网站。
这是我目前所拥有的:
from django.core.serializers.json import DjangoJSONEncoder
from websites.models import Website
class WebsiteEncoder(DjangoJSONEncoder):
def default(self, obj):
raise Exception() # TEST
if isinstance(obj, Website) and hasattr(obj, 'website_ptr'):
return super().default(obj.website_ptr)
return super().default(obj)
我有以下测试用例:
from django.core import serializers
from django.test import TestCase
from websites.models.wordpress import WordpressWebsite
from websites.serialize import WebsiteEncoder
class SerializationTest(TestCase):
def setUp(self):
self.wordpress = WordpressWebsite.objects.create(
domain='test.com'
)
def test_foo(self):
JSONSerializer = serializers.get_serializer("json")
json_serializer = JSONSerializer()
json_serializer.serialize(
WordpressWebsite.objects.all(),
cls=WebsiteEncoder
)
data = json_serializer.getvalue()
print(data)
这个测试用例运行良好。它不会引发异常。
有谁知道为什么 WebsiteEncoder.default 没有被调用?
请您参考如下方法:
Django 模型使用其序列化程序进行本地编码。 Django 自带的DjangoJSONEncoder为具有任何默认 Django 数据类型的所有可能模型提供完整的序列化程序。如果您查看 JSONEncoder.default() documentation ,您会注意到您只会为编码器尚不知道的数据类型提供编码器。
只有当您使用 Django 本身不支持的字段类型时,您才可以为其提供编码器 - 并且只有该字段类型 - 通过 .default() .因此DjangoJSONEncoder不是您要找的。
尝试让您的示例工作时,我发现您实际上可以通过子类化 django.core.serializers.json.Serializer 来自定义流程:
from django.core.serializers.json import Serializer
class WebsiteSerializer(Serializer):
def get_dump_object(self, obj):
return {
"pk": obj.pk,
**self._current,
}
之后,你可以让你的序列化器像这样在测试用例中工作:
def test_foo(self):
serializer = WebsiteSerializer()
data = serializer.serialize(WordpressWebsite.objects.all())
print(data)
