user1403483
user1403483

Reputation:

Django filter ManyToMany field

class Page(models.Model):
    name = models.CharField(max_length=128)
    categories = models.ManyToManyField(Category, null=True, blank=True)

class Category(models.Model):
    # some fields

I want to filter Pages that belong to a particular category. For eg:

filtered_pages = Page.objects.filter(category1 in categories)

I think this should be simple in Django, but can't find a way around it.

Upvotes: 3

Views: 1435

Answers (1)

falsetru
falsetru

Reputation: 368984

Specify categories as a keyword argument:

filtered_pages = Page.objects.filter(categories=category1)

You can also use the category object's page_set to get related pages:

filtered_pages = category1.page_set.all()

Upvotes: 4

Related Questions