django - 覆盖 List 序列化器类中的 to_representation

标签 django python-3.x django-rest-framework django-views django-serializer

我有一个实现 BaseSerializer 的序列化程序我正在使用 to_representation 的类(class)函数进行函数调用,如下所示:

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但它只讨论覆盖创建和更新方法。

最佳答案

您可以访问 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
    ]

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

关于django - 覆盖 List 序列化器类中的 to_representation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52819113/

相关文章:

python - django 上长时间运行的守护进程

django - 图表未在 django-nvd3 中呈现

python - Django Book Ch. 3 : "No Module named mysite.wsgi"

django - 如何在 Django Rest Framework 的自定义字段中传递额外的关键字参数?

html - 图标未出现

python - 删除所有非字母字符,保留字符串中的空格

python-3.x - 为什么 docker 寻找/简单的 python 包?

python-3.x - Azure 文件服务 "PUT Range"REST API 'InvalidHeaderValue' 错误

Django View 中的 Mysql 查询

django - 如何响应通过创建方法(ModelViewSet)插入的不同数据