首页 > 解决方案 > 使用 Django REST 框架进行简单重定向

问题描述

我想做简单的重定向处理。从/api/v1/piyo/piyopiyo/<id>//api/v1/hoge/huga/<id>/

我认为 RedirectView 是可能的,但它循环如下。请告诉我如何设置 urls.py。

网址.py

from rest_framework import routers
from apiv1.views import hoge
from django.urls import include, path

router = routers.SimpleRouter()
router.register('hoge/huga', hoge.HugaViewSet, basename='Huga')
urlpatterns = [
    path('', include(router.urls)),
    # target redirect settings
    re_path(
        'piyo/piyopiyo/.*$',
        RedirectView.as_view( url='hoge/huga')),
]

访问的网址

1. /api/v1/piyo/piyopiyo/346c7932-e9e3-4735-9729-eb50fa29c466/
2. /api/v1/piyo/piyopiyo/346c7932-e9e3-4735-9729-eb50fa29c466/hoge/huga
3. /api/v1/piyo/piyopiyo/346c7932-e9e3-4735-9729-eb50fa29c466/hoge/hoge/huga
...
10. /api/v1/piyo/piyopiyo/346c7932-e9e3-4735-9729-eb50fa29c466/hoge/hoge/hoge/hoge/hoge/hoge/hoge/hoge/hoge/hoge/huga

减少了 10 倍。中止。

路由器.urls

[<URLPattern '^hoge/huga/(?P<pk>[^/.]+)/$' [name='HogeHuga-detail']>]

用 确认print(router.urls)

标签: djangodjango-rest-framework

解决方案


推荐阅读