在列表序列化器类中重写 to_representation

问题描述 投票:0回答:2

我有一个实现

BaseSerializer
类的序列化器,在其中我使用
to_representation
函数来执行如下函数调用:

class ItemSerializer(serializers.BaseSerializer):
    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['log'] = SERVICE.log(instance.id)
        return ret

    class Meta:
        list_serializer_class = ItemListSerializer
        model = models.Item
        fields = '__all__'

我还有一个相同的列表序列化器

ItemListSerializer
,如下所示:

class ItemListSerializer(serializers.ListSerializer):
    def create(self, validated_data):
        items = [models.Item(**item) for item in validated_data]
        return models.Item.objects.bulk_create(items)

我想要做的是当我想要获取整个项目列表时覆盖

to_representation
中的
ItemSerializer
方法。我基本上想避免对每个项目进行函数调用,而是在出于性能原因请求项目列表时对所有项目进行批量调用。

有什么好的方法吗?我按照这些文档创建了

ItemListSerializer
https://www.django-rest-framework.org/api-guide/serializers/#customizing-listserializer-behavior,但它只讨论了重写创建和更新方法。

django python-3.x django-rest-framework django-views django-serializer
2个回答
8
投票

您可以访问

ListSerializer.to_representation

中的所有项目

这应该是一个做你想做的事情的好地方。

方法如下:

def to_representation(self, data):
    """
    List of object instances -> List of dicts of primitive datatypes.
    """
    # Dealing with nested relationships, data can be a Manager,
    # so, first get a queryset from the Manager if needed
    iterable = data.all() if isinstance(data, models.Manager) else data

    return [
        self.child.to_representation(item) for item in iterable
    ]

但说实话,我不知道你能从中得到什么。您的用例看起来不会带来可测量的性能提升。


-1
投票

如果你想避免重复

ListSerializer.to_representation()
的代码,你可以使用它的修补版本,例如
https://github.com/LLyaudet/django-monkey-patches
中的patched_to_representation_v1()https:// github.com/LLyaudet/django-monkey-patches/blob/16d59ca9bbb55451cef7a6097b24bd6ba9e44869/src/django_monkey_patches/django_rest_framework__list_serializer__to_representation.py#L41。 您可以将补丁应用于
ListSerializer
,或者为了获得更好的性能,您可以在继承
ListSerializer
的自定义类中使用它。

© www.soinside.com 2019 - 2024. All rights reserved.