当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自己的} documentation ,您会注意到您只为编码器还不知道的数据类型提供编码器。你知道吗
DjangoJSONEncoder
为所有可能的带有任何默认Django数据类型的模型提供了一个完整的序列化程序。如果您查看^{只有在使用Django本机不支持的字段类型时,才可以通过
.default()
为其提供一个编码器,并且只提供该字段类型。因此DjangoJSONEncoder
不是你想要的。你知道吗我发现,为了使您的示例发挥作用,您实际上可以通过子类化
django.core.serializers.json.Serializer
来定制流程:之后,您可以使序列化程序在测试用例中工作,如下所示:
相关问题 更多 >
编程相关推荐