在布尔值分配中存储布尔变量


问题内容

以下url定义应传递url中是否results/存在:

url(r'^(?P<question_id>[0-9]+)/(?P<results>(results/)?)shorten/$', views.shorten, name='shorten')

当前它已通过results/None足以满足以下要求:

if results:
    pass

但是拥有Trueand会更优雅False。怎么办呢?


问题答案:

您可能有两个URL模式并传入results了kwargs:

url(r'^(?P<question_id>[0-9]+)/results/shorten/$', views.shorten, {'results': True}, name='shorten'),
url(r'^(?P<question_id>[0-9]+)/shorten/$', views.shorten, {'results': False}, name='shorten'),

如果您不想这样做,那么当前还没有一种简单的方法可以将results字符串转换为布尔值。您可以编写一个中间件或装饰器,但这太过分了。