gpt4 book ai didi

python - 为什么 django 不使用我的自定义编码器类?

转载 作者:太空宇宙 更新时间:2023-11-04 04:28:04 26 4
gpt4 key购买 nike

  1. 我有两个类:Website 和 WordpressWebsite。
  2. 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)

关于python - 为什么 django 不使用我的自定义编码器类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53179125/

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