byrdr
byrdr

Reputation: 5487

Django filter objects based on related field

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

Upvotes: 0

Views: 473

Answers (1)

catavaran
catavaran

Reputation: 45595

Do you really mean categories.title = slug?

entries = Entry.live.filter(categories__title=slug)

Upvotes: 1

Related Questions