首页 > 解决方案 > Django Rest Framework - 在单个对象中序列化多个对象

问题描述

我正在尝试在我的项目中集成对外部库的支持。外部库需要一个精确的数据结构,用于调用 response-as-a-table。

我的模型的简单序列化程序可能是:

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'title', 'author')

所以,假设这样的片段:

queryset = Book.objects.all()
serializer = BookSerializer(queryset, many=True)
serializer.data

这给出了这个输出:

[
    {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},
    {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},
    {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}
]

我应该如何重塑我的 BookSerializer 类来实现这个结果?我想不通。

{
    'id': [0, 1, 2],
    'title': ['The electric kool-aid acid test', 'If this is a man', 'The wind-up bird chronicle'],
    'author': ['Tom Wolfe', 'Primo Levi', 'Haruki Murakami']
}

标签: djangopython-2.7django-rest-frameworkserialization

解决方案


覆盖序列化to_representation程序以根据需要重塑输出字典。DRF 没有这样的实用程序,但您可以使用 pandas 轻松实现。例如:

import pandas as pd

def to_representation(self, instance):
    data = super(BookSerializer, self).to_representation(instance)
    df = pd.DataFrame(data=data)
    reshaped_data = df.to_dict(orient='list')
    return reshaped_data

请注意,如果您想将此序列化程序用作视图的一部分,现在数据的形状将不起作用。


推荐阅读