diff options
author | Tim Graham <timograham@gmail.com> | 2016-02-12 14:43:15 -0500 |
---|---|---|
committer | Tim Graham <timograham@gmail.com> | 2016-02-17 13:36:55 -0500 |
commit | 477b82cf8a7eefac98ff4f5afb4754727f4b0004 (patch) | |
tree | 02a442737e2b2511b9d5fcc6386d771e8a2d4cab | |
parent | f78892f2de1e986f00d23581dc006e90e26abd8f (diff) | |
download | django-477b82cf8a7eefac98ff4f5afb4754727f4b0004.tar.gz |
[1.9.x] Fixed #25687 -- Documented how to add database function support to third-party backends.
Thanks Kristof Claes for the initial patch.
Backport of 88034c9938d92193d2104ecfe77999c69301dcc1 from master
-rw-r--r-- | docs/ref/models/expressions.txt | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/docs/ref/models/expressions.txt b/docs/ref/models/expressions.txt index e3078b5449..a580ca426e 100644 --- a/docs/ref/models/expressions.txt +++ b/docs/ref/models/expressions.txt @@ -652,3 +652,34 @@ Let's see how it works:: Apple: AAPL Yahoo: Internet Company 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. |