为什么路径转换器中需要 to_url() 方法?姜戈

wol*_*rus 6 python django url

为什么我需要to_url(self, value)Django 中的路径转换器中的方法?

我在官方文档上只能找到几个例子,无法理解这个方法的用法。

to_url() 到底做了什么?

class FourDigitYearConverter:

    regex = '[0-9]{4}'

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

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

小智 5

URL 反转过程中使用了 Django 转换器中的方法to_url(self, value),该过程涉及根据视图名称及其关联参数生成 URL。

在给定的示例中,假设您有一个使用转换器的视图,如下所示:

urlpatterns = [
    path('my-view/<FourDigitYearConverter:year>/', MyView.as_view(), name='my_view'),
]
Run Code Online (Sandbox Code Playgroud)

在这种情况下,使用反向方法时将调用 to_url 方法来创建 URL,如下所示:

url = reverse('my_view', kwargs={'year': year_value})
Run Code Online (Sandbox Code Playgroud)

如果您尝试对使用缺少 to_url 方法定义的转换器的路径使用反向方法,您将遇到类似以下内容的错误:

AttributeError: 'FourDigitYearConverter' object has no attribute 'to_url'
Run Code Online (Sandbox Code Playgroud)

我希望这能澄清你的问题!


小智 0

此方法将值(例如本例中的数字)转换为可在 URL 中使用的字符串,例如如果该值是整数(例如 4),则它将被格式化为“0004”。