Search code examples
pythondjangodjango-modelsdjango-mpttmptt

django select_related() and django-mptt. How to fetch all the siblings at once?


I'm trying to fetch all the siblings of the current page. The Page model looks like this:

class Page(MPTTModel):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, blank=True) # changing to CharField from SlugField
    markdown = models.TextField()
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True,
                                 blank=True, related_name='children')

The code for fetch all the sublings pages looks like this:

pages = page.get_siblings(include_self=True)

The problem is that the above code hits the database for each page. So If there are 50, it would result in 50 queries.

I have tried to solve the problem using select_related() but to no avail. Here is what I tried.

pages = page.get_siblings(include_self=True).select_related()

# this too doesn't work
pages = page.get_siblings(include_self=True).select_related('parent')

While searching for solutions I stumbled upon this page. Which shows that the select_related() can be called with the get_siblings().

What am I doing wrong?


Solution

  • It turns our that django-mptt was working fine, the culprit was the get_absolute_url() method. I resolved the issue by adding a column to store the url.