Django request select_related how to access grandparent

33 Views Asked by At

I'm constructing a website with a 3-level hierarchy of pages, so my Page model have a foreign key, referring to itself:

class Page(models.Model):       
    ...    
    parent = models.ForeignKey('self', on_delete=models.SET_NULL, 
               blank=True, null=True, 
               related_name='subpages', related_query_name='subs')

When I get a page in my PageDetailView, I want to get it with its parent (if there is one) and a grandparent (if the parent has its parent). If I needed only a parent, it would be quite simple:

page = Page.objects.select_related('parent').get(slug=self.kwargs['slug'])

But I need also to select_related "a parent of parent". I cannot figure out how to do it. It could look like following:

page = Page.objects.select_related(
             'parent',
              Page.objects.select_related('parent' as 'grandparent')
                           ).get(slug=self.kwargs['slug'])

Please give me a hint how to access not only parent but also a grandparent of a page.

1

There are 1 best solutions below

0
D Malan On BEST ANSWER

You can use __ to select relationships. For example:

page = Page.objects.select_related('parent', 'parent__parent').get(slug=self.kwargs['slug'])

Will cache both page.parent and page.parent.parent.