Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top