django rest framework 序列化多个 model 表数据在一个 json 返回中

想要多个model数据序列化在一个返回中,可以使用 DjangoRestMultipleModels
https://github.com/MattBroach/DjangoRestMultipleModels

使用pip安装:

pip install django-rest-multiple-models

ModelSerializers中 配置好后,

在View中使用:
  • 序列化成两个对象的方式
from drf_multiple_model.views import ObjectMultipleModelAPIView

class TextAPIView(ObjectMultipleModelAPIView):
    querylist = [
        {'queryset': Play.objects.all(), 'serializer_class': PlaySerializer},
        {'queryset': Poem.objects.filter(style='Sonnet'), 'serializer_class': PoemSerializer},
        ....
    ]

输出:

{
    "Play" : [
        {"genre": "Comedy", "title": "A Midsummer Night"s Dream", "pages": 350},
        {"genre": "Tragedy", "title": "Romeo and Juliet", "pages": 300},
        ....
    ],
    "Poem" : [
        {"title": "Shall I compare thee to a summer"s day", "stanzas": 1},
        {"title": "As a decrepit father takes delight", "stanzas": 1},
        ....
    ],
}
  • 序列化成一个对象的方式
from drf_multiple_model.views import FlatMultipleModelAPIView

class TextAPIView(FlatMultipleModelAPIView):
    querylist = [
        {'queryset': Play.objects.all(), 'serializer_class': PlaySerializer},
        {'queryset': Poem.objects.filter(style='Sonnet'), 'serializer_class': PoemSerializer},
        ....
    ]

输出:

[
    {"genre": "Comedy", "title": "A Midsummer Night"s Dream", "pages": 350, "type": "Play"},
    {"genre": "Tragedy", "title": "Romeo and Juliet", "pages": 300, "type": "Play"},
    ....
    {"title": "Shall I compare thee to a summer"s day", "stanzas": 1, "type": "Poem"},
    {"title": "As a decrepit father takes delight", "stanzas": 1, "type": "Poem"},
    ....
]

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注