db.models.Func

class Func(*expressions, **extra) [source]

function

A class attribute describing the function that will be generated. Specifically, the function will be interpolated as the function placeholder within template. Defaults to None.

template

A class attribute, as a format string, that describes the SQL that is generated for this function. Defaults to '%(function)s(%(expressions)s)'.

If you’re constructing SQL like strftime('%W', 'date') and need a literal % character in the query, quadruple it (%%%%) in the template attribute because the string is interpolated twice: once during the template interpolation in as_sql() and once in the SQL interpolation with the query parameters in the database cursor.

arg_joiner

A class attribute that denotes the character used to join the list of expressions together. Defaults to ', '.

arity
New in Django 1.10.

A class attribute that denotes the number of arguments the function accepts. If this attribute is set and the function is called with a different number of expressions, TypeError will be raised. Defaults to None.

as_sql(compiler, connection, function=None, template=None, arg_joiner=None, **extra_context) [source]

Generates the SQL for the database function.

The as_vendor() methods should use the function, template, arg_joiner, and any other **extra_context parameters to customize the SQL as needed. For example:

class ConcatPair(Func):
    ...
    function = 'CONCAT'
    ...

    def as_mysql(self, compiler, connection):
        return super(ConcatPair, self).as_sql(
            compiler, connection,
            function='CONCAT_WS',
            template="%(function)s('', %(expressions)s)",
        )
Changed in Django 1.10:

Support for the arg_joiner and **extra_context parameters was added.

The *expressions argument is a list of positional expressions that the function will be applied to. The expressions will be converted to strings, joined together with arg_joiner, and then interpolated into the template as the expressions placeholder.

Positional arguments can be expressions or Python values. Strings are assumed to be column references and will be wrapped in F() expressions while other values will be wrapped in Value() expressions.

The **extra kwargs are key=value pairs that can be interpolated into the template attribute. The function, template, and arg_joiner keywords can be used to replace the attributes of the same name without having to define your own class. output_field can be used to define the expected return type.

doc_Django
2016-10-09 18:35:41
Comments
Leave a Comment

Please login to continue.