xpanta
xpanta

Reputation: 8418

django filter by ManyToManyField of other object

in my models there are two classes:

class PageCategory(models.Model):
    name = models.CharField(max_length=256)
    slug = models.CharField(max_length=256, default='')

class Page(models.Model):
    title = models.CharField(max_length=256)
    slug = models.CharField(max_length=256)
    categories = models.ManyToManyField(PageCategory, related_name='page_categories', null=True, blank=True)

I am trying to retrieve (a) one page to view, and (b) all other pages that belong to the same categories in which that page belongs to in order to list them, too.

This is what I am doing (which is wrong):

def pageView(request, page_slug):
    page = get_object_or_404(Page, slug=unicode(page_slug))
    pages = Page.objects.filter(displayable=True, categories__in=page.categories).exclude(pk=page.id).order_by('-timestamp')

I always get a 'ManyRelatedManager' object is not iterable

How it should be done?

Upvotes: 1

Views: 1143

Answers (1)

Rohan
Rohan

Reputation: 53386

page.categories is a ManyRelatedManager and not a list of categories (which is required for __in check). So you need to specify page.categories.all() to __in filter.

Your query changes to :

pages = Page.objects.filter(displayable=True, 
        categories__in=page.categories.all()).
        exclude(pk=page.id).order_by('-timestamp')

Upvotes: 4

Related Questions