欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

django rest framework如何一次性序列化同一个数据库下多个model表数据在一个json页面下

程序员文章站 2024-03-21 19:55:16
...

在django项目中,首先我们要安装django-rest-mutiple-models

pip install django-rest-multiple-models
然后在setting配置中配置一下APP

INSTALLED_APPS = (
    ....
    'drf_multiple_model',
)

在我们的views视图函数下引入

from drf_multiple_model.views import ObjectMultipleModelAPIView

如下两个模型

class Play(models.Model):
    genre = models.CharField(max_length=100)
    title = models.CharField(max_length=200)
    pages = models.IntegerField()

class Poem(models.Model):
    title = models.CharField(max_length=200)
    style = models.CharField(max_length=100)
    lines = models.IntegerField()
    stanzas = models.IntegerField()

序列化如下

class PlaySerializer(serializers.ModelSerializer):
    class Meta:
        model = Play
        fields = ('genre','title','pages')

class PoemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Poem
        fields = ('title','stanzas')

views中我们可以这么写,继承一个ObjectMutipleModelAPIView

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},
        ....
    ]

如果我们使用的url是router,那这里我们就应该继承ObjectMutipleModelAPIViewset

具体的引入

from drf_multiple_model.viewsets import ObjectMultipleModelAPIViewSet

DRF页面的显示效果如下

{
    "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},
        ....
    ],
}

效果就是能在一个json页面下序列化出多个不同的model数据

我们还可以对每个表的数据进行分页

from drf_multiple_model.pagination import MultipleModelLimitOffsetPagination

views下可以这么写

class LimitPagination(MultipleModelLimitOffsetPagination):

    default_limit = 10

意思是每个model默认显示前十条数据

如果前端需要,url上可以加上limit=5,自定义默认显示前五条数据

更多详细内容,github搜索DjangoRestMultipleModels
原文:https://blog.csdn.net/Z_ForWard/article/details/81666142

上一篇: 带哑头的循环列表

下一篇: 1