6

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.

1 Answer 1

11

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.