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

2024-10-02 18:21:06 发布

您现在位置:Python中文网/ 问答频道 /正文

  1. 我有两个班:网站和WordpressWebsite。你知道吗
  2. WordpressWebsite子类Website。你知道吗

当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没有被调用?你知道吗


Tags: djangofromimportselfjsonobjdefault网站
1条回答
网友
1楼 · 发布于 2024-10-02 18:21:06

Django模型使用其序列化程序进行本机编码。Django自己的DjangoJSONEncoder为所有可能的带有任何默认Django数据类型的模型提供了一个完整的序列化程序。如果您查看^{} 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)

相关问题 更多 >