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

Grant EXECUTE Permissions on all Stored Procedures to a Single User

DECLARE @SQL AS NVARCHAR(MAX);
DECLARE @newline AS NVARCHAR(2);
DECLARE @USER_NAME AS NVARCHAR(100);
DECLARE @sproc_name_pattern AS NVARCHAR(10);

SET @SQL = N”
SET @newline = NCHAR(13) + NCHAR(10);
SET @USER_NAME = N”;

SET @sproc_name_pattern = N’test[_]%’; — Pattern name: select stored procedure which starts with test_

SELECT @SQL = @SQL
+ N’GRANT EXECUTE ON ‘
+ QUOTENAME(OBJECT_SCHEMA_NAME([OBJECT_ID])) + ‘.’
+ QUOTENAME([name])
+ N’ TO ‘
+ QUOTENAME(@USER_NAME)
+ N’;’
+ @newline + @newline
FROM sys.procedures
WHERE [name] LIKE @sproc_name_pattern;

EXEC SP_EXECUTESQL @SQL;

If you have an error says “OBJECT_SCHEMA_NAME …”, you will need to upgrade your SQL Server to 2005 SP2 at least.