Django 2 url路径匹配负值

Pau*_*llo 8 python django django-urls

在Django <2中,正常的方法是使用正则表达式.但现在建议在Django => 2中使用path()而不是url()

path('account/<int:code>/', views.account_code, name='account-code')
Run Code Online (Sandbox Code Playgroud)

这看起来还不错,并且可以很好地匹配url模式

/account/23/
/account/3000/
Run Code Online (Sandbox Code Playgroud)

但是,这个问题是我也希望这个匹配负整数

/account/-23/
Run Code Online (Sandbox Code Playgroud)

请问如何使用path()执行此操作?

nev*_*ner 18

你可以编写自定义路径转换器:

class NegativeIntConverter:
    regex = '-?\d+'

    def to_python(self, value):
        return int(value)

    def to_url(self, value):
        return '%d' % value
Run Code Online (Sandbox Code Playgroud)

在urls.py中:

from django.urls import register_converter, path

from . import converters, views

register_converter(converters.NegativeIntConverter, 'negint')

urlpatterns = [
    path('account/<negint:code>/', views.account_code),
    ...
]
Run Code Online (Sandbox Code Playgroud)