[英]DRF- Django Rest Framework re_path query params - “Method \”GET\“ not allowed.”
I've been trying to GET on generics RetrieveAPIView
class using the re_path method in urls.py file.我一直在尝试使用 urls.py 文件中的 re_path 方法获取 generics RetrieveAPIView
class 。 After trying several combinations, I can only get the path method to work.在尝试了几种组合之后,我只能让路径方法起作用。 I would like to get an endpoint something similar to /file?id={some_uid}
.我想获得一个类似于/file?id={some_uid}
的端点。
So far I have the following:到目前为止,我有以下内容:
views.py:视图.py:
class UploadFileInfoView(generics.RetrieveAPIView):
lookup_field = "id"
queryset = Upload.objects.all()
serializer_class = UploadModelSerializer
urls.py:网址.py:
from django.urls import path, re_path
from . import views
urlpatterns = [
path("file/", views.UploadFileView.as_view(), name="UploadFile"),
# this works
# path("file/<uuid:id>", views.UploadFileInfoView.as_view(), name="UploadFileInfo"),
# this does not
re_path(r"^file/(?P<id>[0-9A-Fa-f-]+)", views.UploadFileInfoView.as_view(), name="UploadFileInfo"),
]
Have not used url method as the documentation says如文档所述,尚未使用 url 方法
This function is an alias to
django.urls.re_path()
.这个 function 是django.urls.re_path()
的别名。 It's likely to be deprecated in a future release.它可能会在未来的版本中被弃用。
As far as I know, Query param is passed to the django views by default.据我所知,查询参数默认传递给 django 视图。 So you don't need to handle it explicitly in the URL.所以你不需要在 URL 中明确地处理它。 In your case if you want /file?id={some_uid}
, you should handle it in the view or overwrite the get_queryset
method.在您的情况下,如果您想要/file?id={some_uid}
,您应该在视图中处理它或覆盖get_queryset
方法。
urlpatterns = [
# ** your other urls **
path(r"file", views.UploadFileInfoView.as_view(), name="UploadFileInfo"),
]
class UploadFileInfoView(generics.ListAPIView):
lookup_field = "id"
queryset = Upload.objects.all()
serializer_class = UploadModelSerializer
def get_queryset(self):
return Upload.objects.get(id=self.request.GET.get('id'))
the above setup will work for /file/?id=1234
and return Upload.objects.get(id=1234)
.上述设置适用于/file/?id=1234
并返回Upload.objects.get(id=1234)
。 I have not tested this code but it should work and also you need to handle exception if the object is not present.我没有测试过这段代码,但它应该可以工作,如果 object 不存在,您还需要处理异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.