在Django的urls.py
#urls.py
url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic')
The second part of the expression, /(?P<topic_id>\d+)/, matches an integer between two forward slashes and stores the integer value in an argument called topic_id.
我尝试用正则表达式来理解它
In [6]: re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/")
Out[6]: ['1']
然而,当我尝试
时In [7]: re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/").topic_id
AttributeError: 'list' object has no attribute 'topic_id'
似乎整数没有存储在topic_id
中,
如何理解?
答案 0 :(得分:5)
您的错误不是来自'topic_id',而是re
。
如果您使用re.findall
,则会返回与您的正则表达式匹配的所有列表。
因此,在您的情况下,re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/")
的结果将是['1']
。
因此,当然,['1'].topic_id
引发了AttributeError。
如果您希望按'topic_id'
分组,请执行此操作
p = re.match(r'topics/(?P<topic_id>\d+)/$', "topics/1/")
p.group('topic_id') # it returns '1'