Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend SQLite with Python functions in Django?

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.

like image 357
akaihola Avatar asked Nov 29 '11 07:11

akaihola


1 Answers

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

like image 131
Visa Kopu Avatar answered Sep 30 '22 16:09

Visa Kopu