Fixed #25687 -- Documented how to add database function support to third-party backends.
Thanks Kristof Claes for the initial patch.
This commit is contained in:
parent
f0425c7260
commit
88034c9938
|
@ -640,3 +640,34 @@ Let's see how it works::
|
||||||
Apple: AAPL
|
Apple: AAPL
|
||||||
Yahoo: Internet Company
|
Yahoo: Internet Company
|
||||||
Django Software Foundation: No Tagline
|
Django Software Foundation: No Tagline
|
||||||
|
|
||||||
|
Adding support in third-party database backends
|
||||||
|
-----------------------------------------------
|
||||||
|
|
||||||
|
If you're using a database backend that uses a different SQL syntax for a
|
||||||
|
certain function, you can add support for it by monkey patching a new method
|
||||||
|
onto the function's class.
|
||||||
|
|
||||||
|
Let's say we're writing a backend for Microsoft's SQL Server which uses the SQL
|
||||||
|
``LEN`` instead of ``LENGTH`` for the :class:`~functions.Length` function.
|
||||||
|
We'll monkey patch a new method called ``as_sqlserver()`` onto the ``Length``
|
||||||
|
class::
|
||||||
|
|
||||||
|
from django.db.models.functions import Length
|
||||||
|
|
||||||
|
def sqlserver_length(self, compiler, connection):
|
||||||
|
return self.as_sql(compiler, connection, function='LEN')
|
||||||
|
|
||||||
|
Length.as_sqlserver = sqlserver_length
|
||||||
|
|
||||||
|
You can also customize the SQL using the ``template`` parameter of ``as_sql()``.
|
||||||
|
|
||||||
|
We use ``as_sqlserver()`` because ``django.db.connection.vendor`` returns
|
||||||
|
``sqlserver`` for the backend.
|
||||||
|
|
||||||
|
Third-party backends can register their functions in the top level
|
||||||
|
``__init__.py`` file of the backend package or in a top level ``expressions.py``
|
||||||
|
file (or package) that is imported from the top level ``__init__.py``.
|
||||||
|
|
||||||
|
For user projects wishing to patch the backend that they're using, this code
|
||||||
|
should live in an :meth:`AppConfig.ready()<django.apps.AppConfig.ready>` method.
|
||||||
|
|
Loading…
Reference in New Issue