来自视图集的 DRF 反向操作 url

DRF reverse action url from viewset

我在 DRF 中反转 ViewSet 操作的 URL 时遇到问题 我的代码在下面,我尝试了一些方法来反转 URLs 但你也可以看到它对我不起作用

view.py

class Device_API(ViewSet):
   
    def list(self, request) -> Response:
        ...

    def update(self, request, pk) -> Response:
        ...
    
    def create(self, request) -> Union[Response, Http404]:
        ...

    
    def destroy(self, request, pk) -> Union[Response, None]:
        ...

    
    @ action(
        detail=False,
        methods=["GET"],
        url_path=r"filter/(?P<type>\w+)",
        url_name="filter_type",
    )
    def filter(self, request, type) -> Union[Response, Http404]:
        ...

    @ action(detail=True, methods=["GET"], url_name="data")
    def data(self, request, pk) -> Union[Response, Http404]:
        ...

urls.py

from rest_framework.routers import DefaultRouter, SimpleRouter
from .views import Device_API

Router = DefaultRouter()
app_name = "api"

Router.register("device", Device_API, basename="Device")
urlpatterns = Router.urls

我尝试像下面那样反转 URL 但我得到一个错误

view = Device_API()
        view.basename = "Device"
        view.request = None
        url = view.reverse_action('filter')

url = reverse('Device-filter')

错误

django.urls.exceptions.NoReverseMatch: Reverse for 'Device-filter' not found. 'Device-filter' is not a valid view function or pattern name.

我也试过这个

url = reverse('api:Device-filter')

错误

Traceback (most recent call last):
  File "/home/nova/Documents/projects/webserver/ENV/lib/python3.8/site-packages/django/urls/base.py", line 71, in reverse
    extra, resolver = resolver.namespace_dict[ns]
KeyError: 'api'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/nova/Documents/projects/webserver/webserver-iot/WEB_SERVER/tests/test_api_v1.py", line 63, in test_test
    url = reverse('api:Device-list')
  File "/home/nova/Documents/projects/webserver/ENV/lib/python3.8/site-packages/django/urls/base.py", line 82, in reverse
    raise NoReverseMatch("%s is not a registered namespace" % key)
django.urls.exceptions.NoReverseMatch: 'api' is not a registered namespace

你的 url 名字是 filter_type

@ action(
        detail=False,
        methods=["GET"],
        url_path=r"filter/(?P<type>\w+)",
        url_name="filter_type",
    )

所以尝试:

url = reverse('api:Device-filter_type')
or
url = reverse('api:Device-filter-type')

我通过在 urls.py 的 URL 中添加一个 命名空间 解决了这个问题

urls.py

path("", include("my_app.urls", "API")),

我可以通过这些方法检索 URL

from django.urls import reverse from rest_framework.reverse import reverse

url = reverse("API:Device-list") 
#              {basenam}-method-name

并且您可以通过这种方式为您的视图设置基本名称

my_app/urls.py

from rest_framework.routers import DefaultRouter
from .views import My_View

Router = DefaultRouter()
Router.register("device", Device_API, basename="Device")
urlpatterns = Router.urls