Django视图中url确认的一些问题

发布于 2024-08-08 17:58:55 字数 531 浏览 5 评论 0 原文

我的模特:

故事:

categories = models.ManyToManyField(Category)

类别:姓名| slug

我的网址:

(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, })

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

My models:

Story:

categories = models.ManyToManyField(Category)

Category: name | slug

My urls:

(r'^(?P<cat_slug>.*)/

And in views, I use:

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

It has something wrong if I have a story of two or more category. Please help me. Many thanks!

, 'news.views.archive_category'),

And in views, I use:


It has something wrong if I have a story of two or more category. Please help me. Many thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纸伞微斜 2024-08-15 17:58:55
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

评论后编辑

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

edited after comment

谈下烟灰 2024-08-15 17:58:55

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

News.objects.get()总是获取单个项目,如果有多个项目匹配条件,则会引发异常。您应该使用 filter() 来代替,将 QuerySet 传递给模板,这样您就需要进行迭代;或者,向您的 urlconf 添加一个条件,以便您也获得特定的条目 slug,这样您就只能获得一个对象。

What do you want to happen in this circumstance? Are you trying to show a list of all the entries in a category, or just one?

News.objects.get() will always get a single item, or raise an exception if there are more than one matching the criteria. Either you should use filter() instead, passing a QuerySet to the template, so you'll need to iterate through; or, add a criteria to your urlconf so that you get the specific entry slug as well, so you only get one object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文