DRF如何从多个模型获取行数

时间:2019-02-22 08:34:02

标签: django django-rest-framework

我有两个模型,如何通过一个请求获得每个模型的行数(使用DRF)?

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

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

2 个答案:

答案 0 :(得分:0)

您只需要获取计数并像下面这样简单地传递计数即可:

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)

答案 1 :(得分:0)

编写一个视图并覆盖get方法。

 class TotalCountAPIView(RetrieveAPIView):
        def get(self, request, *args, **kwargs):
            count_qsn = Question.objects.count()
            count_srvc = Service.objects.count()
            return Response(data= {'count_qsn':count_qsn, 'count_srvc': count_srvc})