首页 > 解决方案 > DRF how can get count of rows from multiple models

问题描述

I have two models, how can I get the count of rows each of them(using DRF) by one request?

class Question(AbstractArticle):
    title = models.CharField(max_length=256, unique=True)

class Service(models.Model):
    name = models.CharField(max_length=256)

标签: djangodjango-rest-framework

解决方案


您只需要像这样简单地获取计数并传递它:

from rest_framework.views import APIView
from models import Question,Service
from rest_framework import status
class GetCount(APIView):
    #use your proper authentication/permission classes here
    def get(self,request):
        question_count=Question.objects.count()
        service_count= Service.objects.count() 

        return Response({"question":question_count,"service":service_count},status=status.HTTP_200_OK)

推荐阅读