若是你有一個需求, 你開發的 Django 項目 API 中須要同時返回兩個模型類的序列化數據, 這個時候你可能會想, 能夠一個個實現查詢, 在用 Response 對象返回就行了。 那我偏不!html
Django 組件 django-rest-multiple-models
幫你知足你的需求, 能夠實現多個模型的序列化, 只須要你的配置信息便可。python
使用 Python-pip
安裝:shell
python3 -m pip install django-rest-multiple-models
複製代碼
在 Django 項目 settings.py
中註冊組件 APP:django
INSTALLED_APPS = [
...
'drf_multiple_model',
]
複製代碼
這時候你就能夠導入模塊並實現你的功能了, 如:json
# 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')
複製代碼
在上面的案例中咱們定義了 Models 和 Serializer, 如今能夠直接撰寫 API 視圖類:spa
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},
]
複製代碼
你就能夠獲取到相似於下面的響應數據:rest
{
'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},
...
]
}
複製代碼
你也能夠使用 FlatMultipleModelAPIView
來繼承:code
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},
...
]
複製代碼
你將會獲得:cdn
[
{'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'},
...
]
複製代碼
固然能夠進行過濾和分頁, 以及其餘的屬性, 如使用標籤等等, 給個文檔給你吧:官方說明文檔htm
Success is the ability to go from one failure to another with no loss of enthusiasm. — Winston Churchill
成功是一我的從一次失敗走向另外一次失敗而沒有喪失熱情的能力。---溫斯頓邱吉爾