在个别开发中,我们经常能遇到同一个数据连接显示很多个model数据的json,即同一个index.json页面中,既有category的数据,也有products的数据,在同一页面显示多条分类下的数据,如下图: 如果我们想在django中这样显示,该怎么做呢

使用DRF快速序列化

假设我们有两个model,并使用DRF的serializers.ModelSerializer序列化过了

# Models
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()

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

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

django-rest-multiple-models

如果我们想要达到上图的效果,很显然,这个得从视图中下手

pip install django-rest-multiple-models

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

然后在视图中导入以下方法

from drf_multiple_model.views import ObjectMultipleModelAPIView

然后编写视图;

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

最后导入路由就可以啦

drf_multiple_model.views中有两个类,具体可阅读以下源码,都是基于DRF的

效果查看

[
    {"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"},
    ....
]
最后修改:2020年7月23日 15:26