Django @property executes extra database calls? Ensure using cached result instead.

People made mistakes as below code that executes database call every time it’s invoked.

class MyModel(models.Model):
    @property
    def is_ready(self):
        status = self.check_status_from_db()
        return True if status else None

Assuming that there’re 2 or more {{ object.is_ready }} in your template especially in a loop on a list page. See what would happen via django debug toolbar.

Let’s fix the issue with the below code.

class MyModel(models.Model):
    @property
    def is_ready(self):
        if not hasattr(self, '_is_ready'):
            status = self.check_status_from_db()
            self._is_ready = True if status else None
        return self._is_ready

Now, retest the code and see what’s difference.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s