如何在Django中使用Python函数扩展SQLite? [英] How to extend SQLite with Python functions in Django?

查看:52
本文介绍了如何在Django中使用Python函数扩展SQLite?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以为Python中的SQLite定义新的SQL函数。我该如何在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?

一个示例用例是使用 GREATEST()和LEAST() PostgreSQL函数,在SQLite中不可用。我的测试套件运行此查询,并且我希望能够在运行测试时将SQLite用作数据库后端。

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.

推荐答案

这是一个Django代码示例,该示例通过调用Python的内置max()和min()来扩展具有GREATEST()和LEAST()方法的SQLite:

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)

我只在测试中需要它,因此将其放在test_settings.py中。如果您在代码的其他位置使用它,则可能需要测试 connection.vendor == sqlite

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

这篇关于如何在Django中使用Python函数扩展SQLite?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆