0

我的模型:

故事:

categories = models.ManyToManyField(Category)

类别:姓名 | 蛞蝓

我的网址:

(r'^(?P<cat_slug>.*)/$', 'news.views.archive_category'),

视图中,我使用:

def archive_category(request, cat_slug):
    entry = News.objects.get( categories__slug=cat_slug )
    return render_to_response('news_archive_category.html', {'entry':entry, })

如果我有两个或更多类别的故事,那就有问题了。请帮我。非常感谢!

4

2 回答 2

0

在这种情况下你想发生什么?您是要显示一个类别中所有条目的列表,还是只显示一个?

News.objects.get()始终获得一个项目,或者如果有多个匹配条件则引发异常。您应该filter()改用,将 QuerySet 传递给模板,因此您需要遍历;或者,在您的 urlconf 中添加一个标准,以便您也获得特定的条目 slug,因此您只会获得一个对象。

于 2009-10-22T09:25:15.997 回答
0
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

评论后编辑

于 2009-10-22T22:54:49.450 回答