这是我的观点
class FindKeyWordNews(ListAPIView):
queryset = []
serializer_class = KeyWordSerializers
def get_queryset(self):
query_list = []
keyword = self.kwargs.get("keyword")
if keyword:
republic = Republic.objects.filter(Q(headline__icontains=keyword)).order_by('-id')
ndtv = Ndtv.objects.filter(Q(headline__icontains=keyword)).order_by('-id')
indiatoday = Indiatv.objects.filter(Q(headline__icontains=keyword)).order_by('-id')
hindustan = Hindustan.objects.filter(Q(headline__icontains=keyword)).order_by('-id')
thehindu = Thehindu.objects.filter(Q(headline__icontains=keyword)).order_by('-id')
zee = Zeenews.objects.filter(Q(headline__icontains=keyword)).order_by('-id')
query_list = list(chain(republic, ndtv, indiatoday, hindustan, thehindu, zee))
return query_list
我知道为单个模型创建序列化程序类
class NdtvSerializers(serializers.ModelSerializer):
class Meta:
model =Ndtv
fields = ('headline', 'link', 'date', 'category', 'sentiment')
如何为上述视图的多个模型创建序列化程序类?模型的架构是相同的。
经过一些研究,我发现这个文档 rest 多个模型和包含 django rest 多个模型的步骤在这里 django rest 多个模型在项目中之后,我需要在我的视图中更改以下代码,并通过以下方式对所有模型使用序列化:
class FindKeyWordNews(ObjectMultipleModelAPIView):
querylist = []
def get_querylist(self, *args, **kwargs):
keyword = self.kwargs.get("keyword")
print(keyword)
if keyword:
queryset = [
{'queryset': Republic.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': RepublicSerializers},
{'queryset': Ndtv.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': NdtvSerializers},
{'queryset': Indiatv.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': IndiatvSerializers},
{'queryset': Hindustan.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': HindustanSerializers},
{'queryset': Thehindu.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': TheHinduSerializers},
{'queryset': Zeenews.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': ZeeNewsSerializers},
{'queryset': News18.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': News18Serializers},
{'queryset': Firstpost.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': FirstpostSerializers},
{'queryset': Indianexpress.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': IndianexpressSerializers},
{'queryset': Oneindia.objects.filter(Q(headline__icontains=keyword)).order_by('-id'),
'serializer_class': OneindiaSerializers},
]
return queryset
我很高兴我的代码工作正常并创建 api。