在Django视图中确认URL的一些问题
-
05-07-2019 - |
题
我的模特:
故事:
categories = models.ManyToManyField(Category)
类别:名称|蛞蝓
我的网址:
(r'^(?P<cat_slug>.*)/
在观看次数中,我使用:
def archive_category(request, cat_slug):
entry = News.objects.get( categories__slug=cat_slug )
return render_to_response('news_archive_category.html', {'entry':entry, })
如果我有两个或更多类别的故事,那就错了。请帮我。非常感谢!
, 'news.views.archive_category'),
在观看次数中,我使用:
<*>如果我有两个或更多类别的故事,那就错了。请帮我。非常感谢!
解决方案
category = Category.objects.filter(slug=cat_slug)#get the category requested
#now get all the entries which have that category
entries = News.objects.filter(categories__in=category)#because of the many2many use __in
在评论后编辑
其他提示
在这种情况下你想要发生什么?您是要尝试显示某个类别中所有条目的列表,还是只显示一个?
News.objects.get()
将始终获取单个项目,或者如果有多个匹配条件,则引发异常。您应该使用 filter()
,将QuerySet传递给模板,因此您需要迭代;或者,在urlconf中添加一个条件,以便获得特定的条目slug,这样你只能得到一个对象。
不隶属于 StackOverflow