我有一个ListCreateAPIView,我试图覆盖get_queryset,但从未调用过它。这是我的观点:
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
?
答案 0 :(得分:1)
从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)
因此,您可能缺少列表中的超级调用或self.filter_queryset调用。这些将确保get_queryset被调用。