It's possible to define new SQL functions for SQLite in Python. How can I do this in Django so that the functions are available everywhere?

An example use case is a query which uses the GREATEST() and LEAST() PostgreSQL functions, which are not available in SQLite. My test suite runs this query, and I'd like to be able to use SQLite as the database backend when running tests.

up vote 10 down vote accepted

Here's a Django code example that extends SQLite with GREATEST() and LEAST() methods by calling Python's built-in max() and min():

from django.db.backends.signals import connection_created
from django.dispatch import receiver

@receiver(connection_created)
def extend_sqlite(connection=None, **kwargs):
    connection.connection.create_function("least", 2, min)
    connection.connection.create_function("greatest", 2, max)

I only needed this in the tests, so I put this in my test_settings.py. If you have it elsewhere in your code, you may need to test that connection.vendor == "sqlite".

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.