【问题标题】:Django Rest Framework - Serialize multiple objects in a single objectDjango Rest Framework - 在单个对象中序列化多个对象
【发布时间】:2019-03-16 10:41:51
【问题描述】:

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

我的模型的简单序列化器可以是:

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

所以,假设一个像这样的 sn-p:

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']
}

【问题讨论】:

  • 你为什么想要这种行为?看起来你可以在你的视图中做到这一点,只需通过迭代查询集而不使用序列化程序来构建你的字典。但我不确定这是一个好方法。
  • 我需要这种行为,因为绘图库需要这种数据结构:(
  • @MilesDavis 正如 Chiefir 提到的,您可以在视图级别执行此操作。
  • 只转换你的查询集,你不需要序列化器

标签: django python-2.7 django-rest-framework serialization


【解决方案1】:

覆盖序列化程序的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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 2017-07-12
    • 2016-10-22
    • 2015-08-15
    • 1970-01-01
    • 2021-11-30
    • 2014-07-07
    相关资源
    最近更新 更多