我的网站针对不同类别有不同的网址,它会根据类别返回过滤后的查询集,例如/sport/
将返回 Post.objects.filter(category='sport')
网址
urlpatterns = [
url(r'^news/$', boxes_view, name='news'),
url(r'^sport/$', boxes_view, name='sport'),
url(r'^technology/$', boxes_view, name='technology'),
url(r'^science/$', boxes_view, name='science'),
url(r'^cars/$', boxes_view, name='cars'),
url(r'^television/$', boxes_view, name='television'),
url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article'),
查看
def boxes_view(request):
category = 'news'
for a, b in CATEGORY_CHOICES:
name = resolve(request.path_info).url_name
if b == name:
category = a
posts = Post.objects.all().filter(category=category)
选择.py
CATEGORY_CHOICES = (
('1', 'news'),
('2', 'sport'),
('3', 'technology'),
('4', 'science'),
('5', 'cars'),
('6', 'television')
)
我是否可以只编写 1 个统一的 url 模式来解释所有类别,而不是列出我的 url 中的每个类别?
最佳答案
是的。事实上,看起来你已经成功了。您可以使用正则表达式来识别类别名称并将其传递到 View ,就像处理列表中最后一个 url(“文章”)一样。
尝试这样的事情:
urlpatterns = [
url(r'^(?P<category>\w+)/$', boxes_view, name='category'), #or whatever name
url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article'),
]
那么你的 View 将类似于:
def boxes_view(request, category='news'):
try:
category_number = CATEGORY_MAP[category]
except KeyError:
# return 404?
posts = Post.objects.filter(category=category_number)
...
然后,您将需要一个类别映射,它就像您的元组一样,但我会使用如下字典:
CATEGORY_MAP = {
'news': 1,
...
}
尽管我需要查看您的更多架构才能确定,但从我所看到的情况来看,我建议类别应该是它们自己的模型,然后您可以在 中执行
过滤器并删除从名称到号码的映射。category__name
>发布
关于python - 尝试组织我的网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42685767/