views:

36

answers:

2

My models:

Story:

categories = models.ManyToManyField(Category)

Category: name | slug

My urls:

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

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!

A: 

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.

Daniel Roseman
Use the filter is the options simpler.
Tran Tuan Anh
A: 
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

Brandon H
Thank you. But if we do this will be generated error: 'Category' object is not iterable.
Tran Tuan Anh
my bad. use filter instead of get. then there is no need for the try/except. the queryset is iterable.
Brandon H
no need for the try/except error-wise, but you may want to do something to catch if there are no entries. on my multiblog i just leave it alone and display the requested page with no entries.
Brandon H