分页查询查询重复,为什么查询不止一次?
Pagination query query duplicated, why is the query more than once?
为什么查询重复?有什么我没注意到的吗?
有什么办法可以优化吗?
分页
class MyPageNumberPagination(PageNumberPagination):
page_size = 2
page_size_query_param = 'size'
max_page_size = 4
def get_paginated_response(self, data):
return Response({
'page': self.page.number,
'total_pages': self.page.paginator.num_pages,
'count': self.page.paginator.count,
'data': data
})
浏览量不使用分页。
class DevicesView(ModelViewSet):
serializer_class = DeviceSerializer
queryset = DeviceModel.objects.all()
def list(self, request, *args, **kwargs):
queryset = DeviceModel.objects.filter(owner_id__owner__id=request.user.pk)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
浏览量使用分页。
class DevicesView(ModelViewSet):
serializer_class = DeviceSerializer
queryset = DeviceModel.objects.all()
pagination_class = MyPageNumberPagination
def list(self, request, *args, **kwargs):
queryset = DeviceModel.objects.filter(owner_id__owner__id=request.user.pk)
page = self.paginate_queryset(queryset)
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
您正在访问 queryset
两次。一种分页,一种仅用于序列化程序:
page = self.paginate_queryset(queryset) # <---- Hits DB
serializer = self.get_serializer(queryset, many=True) # <---- Hits DB again
您应该将页面传递给序列化程序:
serializer = self.get_serializer(page, many=True)
为什么查询重复?有什么我没注意到的吗?
有什么办法可以优化吗?
分页
class MyPageNumberPagination(PageNumberPagination):
page_size = 2
page_size_query_param = 'size'
max_page_size = 4
def get_paginated_response(self, data):
return Response({
'page': self.page.number,
'total_pages': self.page.paginator.num_pages,
'count': self.page.paginator.count,
'data': data
})
浏览量不使用分页。
class DevicesView(ModelViewSet):
serializer_class = DeviceSerializer
queryset = DeviceModel.objects.all()
def list(self, request, *args, **kwargs):
queryset = DeviceModel.objects.filter(owner_id__owner__id=request.user.pk)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
浏览量使用分页。
class DevicesView(ModelViewSet):
serializer_class = DeviceSerializer
queryset = DeviceModel.objects.all()
pagination_class = MyPageNumberPagination
def list(self, request, *args, **kwargs):
queryset = DeviceModel.objects.filter(owner_id__owner__id=request.user.pk)
page = self.paginate_queryset(queryset)
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
您正在访问 queryset
两次。一种分页,一种仅用于序列化程序:
page = self.paginate_queryset(queryset) # <---- Hits DB
serializer = self.get_serializer(queryset, many=True) # <---- Hits DB again
您应该将页面传递给序列化程序:
serializer = self.get_serializer(page, many=True)