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.
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With