1

我有一个试图覆盖 get_queryset 的 ListCreateAPIView,但它从未被调用过。这是我的看法:

class DeviceView(generics.ListCreateAPIView):
    def get_queryset(self):
        # Threw this and some print statements, but no sign of 
        # the exception or print statement
        raise Exception
        return None
    @swagger_auto_schema(
        responses={
            201: DeviceSerializer(),
        },
        request_body=DeviceSerializer,
    )
    def post(self, request, format=None):
        # This code works fine
        ...
    @swagger_auto_schema(responses={200: DeviceSerializer(many=True)})
    def get(self, request, format=None):
        # This code DOES get hit and successfully retrieves all the devices

这是 urls.py:

urlpatterns = [
    path(r"devices/<serialnumber>/abc", views.AbcView.as_view()),
    path(r"devices/<serialnumber>", views.DeviceDetailView.as_view()),
    path(r"devices/", views.DeviceView.as_view()),
    path(r"api-auth/", include("rest_framework.urls", namespace="rest_framework")),
    path(
        r"swagger/",
        schema_view.with_ui("swagger", cache_timeout=0),
        name="schema-swagger-ui",
    ),
    url(
        r"^swagger(?P<format>\.json|\.yaml)$",
        schema_view.without_ui(cache_timeout=0),
        name="schema-json",
    ),
    url(r"^api-token-auth/", obtain_jwt_token),
    path("admin/", admin.site.urls),
]

get_queryset关于为什么没有被击中/覆盖的任何想法?

4

1 回答 1

2

来自django rest框架代码

class ListAPIView(mixins.ListModelMixin,
                  GenericAPIView):
    """
    Concrete view for listing a queryset.
    """
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

所以首先,最好覆盖list函数而不是get.

class ListModelMixin(object):
    """
    List a queryset.
    """
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

所以你可能错过了 list 中的 super 调用或 self.filter_queryset 调用。这些将确保调用 get_queryset。

于 2018-11-29T13:30:19.727 回答