TransWikia.com

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

Stack Overflow Asked on November 12, 2021

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?

2 Answers

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.

Answered by Cody on November 12, 2021

Did you try to use the standard way to access sibling/parent objects in the Django Model paradigm?

You can find an example here:

In your particular case the snippet should be the following:

MPTTModel.objects.filter(page__pk=page.pk)

Answered by Williams Rizzi on November 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP