django - 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']
}
解决方案
覆盖序列化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
请注意,如果您想将此序列化程序用作视图的一部分,现在数据的形状将不起作用。
推荐阅读
- mongodb - Mongodb 多语言搜索:哪种模式更适合更快的搜索结果 - 嵌套或直接具有特定于语言的字段
- apache - 如何在 .htaccess 中使用自定义逻辑重定向 url?
- python - 使用正则表达式查找包含重复单词的句子
- html - 当我直接点击时,HTML 无法加载 CSS,但是当我使用 VSCode 上线时,它加载得很好
- python - 如何仅从 DateTime 对象中检索时间但保留数据类型
- android - 有没有办法以编程方式将文件从 Android 应用程序上传到 Google Drive?
- python - 我如何显示可视化的价值
- python - 将熊猫数据框列值从字符串转换为浮点数
- javascript - Angular 中的用户 JsonWebToken -> 方法发布
- java - 未知方言支持 REF_CURSOR 参数