4

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?

Cody
  • 2,480
  • 5
  • 31
  • 62
  • 1
    I couldn't reproduce the *n* queries. What does your tree look like? – aaron Jul 22 '20 at 16:14
  • The culprit was the `get_absolute_url()` method. It was getting called for each page. I resolved it by adding a column to store the url. That's it. should I close the question? – Cody Jul 22 '20 at 17:16
  • If it was resolved in a way that is unlikely to help future readers, then yes. – aaron Jul 22 '20 at 17:27

2 Answers2

1

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)

  • 1
    Thanks for the reply. But It turns our that django-mptt was working fine, the `get_absolute_url()` method was causing the issue. – Cody Jul 22 '20 at 17:19
1

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.

Cody
  • 2,480
  • 5
  • 31
  • 62