Writing your own function

To create your own custom function, you just need to register it. The first argument to nlf_function will determine how the function can be referenced in filter expressions, the role parameters determines where the function can be used, while the model parameter can be used to restrict usability to certain models.

See the following example:

from django_nlf.functions import nlf_function

@nlf_function("myFunction")
def my_function(*args, **kwargs):
  pass

The arguments are passed as strings as positional arguments, only quotes are removed. Additional context is available through key word arguments.

Currently the Model class being filtered, the Request and the View are passed as model, request and view respectively.

Value functions

If the function is used as a value, it can return anything appropriate for the field.

Field functions

If the function is used as a field, it must return a dictionary with a single key, the field name, and an annotation. This can be an F object, Aggragation, Subquery or even a Window.

Warning

Annotations are applied BEFORE all other filtering is done, therefore if you need to filter on a group, that must be handled as an expression function with a Subquery.

Expression functions

Expression functions are passed an additional keyword argument exclude to specify if the function has been negated (exclude=True) or not (exclude=False). It must return a tuple of a dictionary holding annotations as for field functions and a Q object.

Warning

Annotations are applied BEFORE all other filtering is done, therefore if you need to filter on a group, that must be handled as an expression function with a Subquery.