0

I have a blog setup with Entries with a many to many field to Categories.

categories = models.ManyToManyField(Category)

I have a view in which I'd like to list all of the Entries, but filter based on Entries that have a relation to the Category, which will be represented in the url as a slug.

Here is my view function so far:

def category_detail(self, request, slug):
  entries = Entry.live.all().filter()
  categories = Category.objects.all()
  return render(request, 'coltrane/entry_archive.html', 
   {"entries": entries, "categories": categories})

A category list is appearing in the sidebar, which is why I'm passing those values in the dict. I'd like to add some logic in the entries filter to return something along the lines of categories.title = slug

2
  • It's very easy to do what you are asking but your question is not clear. Please show more of your models and specify the exact filtering you require. Commented Jan 14, 2015 at 16:33
  • Example: categories.title = slug. What is the value of slug and where does it come from? Is slug unique? Commented Jan 14, 2015 at 16:34

1 Answer 1

1

Do you really mean categories.title = slug?

entries = Entry.live.filter(categories__title=slug)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, easier than I thought.
You can even leave out .all() -- it is implied for operations like filter() and only explicitly required on an unfiltered delete.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.