1
from rest_framework.viewsets import ReadOnlyModelViewSet
from drf_renderer_xlsx.mixins import XLSXFileMixin
from drf_renderer_xlsx.renderers import XLSXRenderer
from .models import MyExampleModel
from .serializers import MyExampleSerializer

class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
    serializer_class = MyExampleSerializer
    renderer_classes = [XLSXRenderer]
    filename = 'my_export.xlsx'

    def get_queryset(self):
        start_date = self.request.query_params.get('start_date', None)
        end_date = self.request.query_params.get('end_date', None)
        queryset = MyExampleModel.objects..filter(created__range=[start_date, end_date])
        Return queryset

        # What I want to do
        # If not queryset:
        #    Return Response({"message": "Exporting Fail"})
        

# Is there a way to check if queryset is None and return a Error Message instead of an empty Excel
# I think that I not allow return Response in the get_queryset function

目前,我正在尝试构建一个导出 excel 文件的函数。我只想知道有没有办法检查查询集是否为 None 然后我可以返回一个 Response({"message": "Exporting Fail, Empty"})

如果你知道我在哪里可以研究它会对我有很大帮助。太感谢了

4

1 回答 1

0

您应该进行过滤,filter_queryset或者get_queryset您已经拥有的内容是正确的。但get_queryset必须返回一个queryset,而不是一个Response对象。

您将访问get_object方法中的实际对象。


    def get_object(self):
        """
        Returns the object the view is displaying.

        You may want to override this if you need to provide non-standard
        queryset lookups.  Eg if objects are referenced using multiple
        keyword arguments in the url conf.
        """
        queryset = self.filter_queryset(self.get_queryset())

        # Perform the lookup filtering.
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

        assert lookup_url_kwarg in self.kwargs, (
            'Expected view %s to be called with a URL keyword argument '
            'named "%s". Fix your URL conf, or set the `.lookup_field` '
            'attribute on the view correctly.' %
            (self.__class__.__name__, lookup_url_kwarg)
        )

        filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
        obj = get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj

如果您不想在查询集为空时引发 404,则必须首先调整最后几行。

retrieve然后,您只能list在您的视图集中相应地调整这些方法。


    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        if not instance:
            return Response({"message": "Exporting Fail"})
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

或者你根本不改变get_object并处理 404

    def retrieve(self, request, *args, **kwargs):
        try:
            instance = self.get_object()
            serializer = self.get_serializer(instance)
            return Response(serializer.data)
        except Http404:
            return Response({"message": "Exporting Fail"})

但 imo 这不是一个干净的解决方案。

于 2021-05-13T07:48:49.967 回答