0

In all my models I have a get_absolute_url() method as the one below, but with django-debug-toolbar I see that it costs many SQL queries.

My objects are related in a tree structure, so a level 3 object only knows what level 1 object it is related to through level 2. How can I avoid these many SQL queries? Is it bad practice to relate objects through other objects? Do I have to save the level 1 slug and level 2 slug as CharFields in my level 3 model?

@models.permalink
def get_absolute_url(self):
    return ('url_alias', None, {'level1': self.level2.level1.slug, 'level2': self.level2.slug, 'level3': self.slug})
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
Jamgreen
  • 10,329
  • 29
  • 113
  • 224

1 Answers1

1

Are the slugs on your site permanent? If so, it is needless work to constantly calculate your URL like this. If your slugs are permanent, you could add a listener for saves on your model, and, at saving-time, populate a field with the URL to the object. Then your get_absolute_url could just show that.

If your slugs are not permanent, you could do as Matthew Daly suggested and store the URL-for-this-object in a cache bucket and check that. You'd still have to figure out how you wanted to clear that key (since it would need to change if you changed the slug for this object or any object higher up in the URL path).

Joel Burton
  • 1,466
  • 9
  • 11