Lookup API referenceLink to this heading
This document has the API references of lookups, the Django API for building
the WHERE clause of a database query. To learn how to use lookups, see
Making queries; to learn how to create new lookups, see
How to write custom lookups.
The lookup API has two components: a RegisterLookupMixin
class that registers lookups, and the Query Expression API, a set of methods that a class has to implement to be
registrable as a lookup.
Django has two base classes that follow the query expression API and from where all Django builtin lookups are derived:
A lookup expression consists of three parts:
Fields part (e.g.
Book.objects.filter(author__best_friends__first_name...);Transforms part (may be omitted) (e.g.
__lower__first3chars__reversed);A lookup (e.g.
__icontains) that, if omitted, defaults to__exact.
Registration APILink to this heading
Django uses RegisterLookupMixin to give a class the interface
to register lookups on itself or its instances. The two prominent examples are
Field, the base class of all model fields, and
Transform, the base class of all Django transforms.
- class lookups.RegisterLookupMixinLink to this definition
A mixin that implements the lookup API on a class.
- classmethod register_lookup(lookup, lookup_name=None)Link to this definition
Registers a new lookup in the class or class instance. For example:
DateField.register_lookup(YearExact) User._meta.get_field("date_joined").register_lookup(MonthExact)will register
YearExactlookup onDateFieldandMonthExactlookup on theUser.date_joined(you can use Field Access API to retrieve a single field instance). It overrides a lookup that already exists with the same name. Lookups registered on field instances take precedence over the lookups registered on classes.lookup_namewill be used for this lookup if provided, otherwiselookup.lookup_namewill be used.
- get_lookup(lookup_name)Link to this definition
Returns the
Lookupnamedlookup_nameregistered in the class or class instance depending on what calls it. The default implementation looks recursively on all parent classes and checks if any has a registered lookup namedlookup_name, returning the first match. Instance lookups would override any class lookups with the samelookup_name.
- get_lookups()Link to this definition
Returns a dictionary of each lookup name registered in the class or class instance mapped to the
Lookupclass.
- get_transform(transform_name)Link to this definition
Returns a
Transformnamedtransform_nameregistered in the class or class instance. The default implementation looks recursively on all parent classes to check if any has the registered transform namedtransform_name, returning the first match.
For a class to be a lookup, it must follow the Query Expression API. Lookup and Transform naturally
follow this API.
The Query Expression APILink to this heading
The query expression API is a common set of methods that classes define to be
usable in query expressions to translate themselves into SQL expressions.
Direct field references, aggregates, and Transform are examples that follow
this API. A class is said to follow the query expression API when it implements
the following methods:
- as_sql(compiler, connection)Link to this definition
Generates the SQL fragment for the expression. Returns a tuple
(sql, params), wheresqlis the SQL string, andparamsis the list or tuple of query parameters. Thecompileris anSQLCompilerobject, which has acompile()method that can be used to compile other expressions. Theconnectionis the connection used to execute the query.Calling
expression.as_sql()is usually incorrect - insteadcompiler.compile(expression)should be used. Thecompiler.compile()method will take care of calling vendor-specific methods of the expression.Custom keyword arguments may be defined on this method if it’s likely that
as_vendorname()methods or subclasses will need to supply data to override the generation of the SQL string. SeeFunc.as_sql()for example usage.
- as_vendorname(compiler, connection)Link to this definition
Works like
as_sql()method. When an expression is compiled bycompiler.compile(), Django will first try to callas_vendorname(), wherevendornameis the vendor name of the backend used for executing the query. Thevendornameis one ofpostgresql,oracle,sqlite, ormysqlfor Django’s built-in backends.
- get_lookup(lookup_name)Link to this definition
Must return the lookup named
lookup_name. For instance, by returningself.output_field.get_lookup(lookup_name).
- get_transform(transform_name)Link to this definition
Must return the lookup named
transform_name. For instance, by returningself.output_field.get_transform(transform_name).
- output_fieldLink to this definition
Defines the type of class returned by the
get_lookup()method. It must be aFieldinstance.
Transform referenceLink to this heading
- class TransformLink to this definition
A
Transformis a generic class to implement field transformations. A prominent example is__yearthat transforms aDateFieldinto aIntegerField.The notation to use a
Transformin a lookup expression is<expression>__<transformation>(e.g.date__year).This class follows the Query Expression API, which implies that you can use
<expression>__<transform1>__<transform2>. It’s a specialized Func() expression that only accepts one argument. It can also be used on the right hand side of a filter or directly as an annotation.- bilateralLink to this definition
A boolean indicating whether this transformation should apply to both
lhsandrhs. Bilateral transformations will be applied torhsin the same order as they appear in the lookup expression. By default it is set toFalse. For example usage, see How to write custom lookups.
- lhsLink to this definition
The left-hand side - what is being transformed. It must follow the Query Expression API.
- lookup_nameLink to this definition
The name of the lookup, used for identifying it on parsing query expressions. It cannot contain the string
"__".
- output_fieldLink to this definition
Defines the class this transformation outputs. It must be a
Fieldinstance. By default is the same as itslhs.output_field.
Lookup referenceLink to this heading
- class LookupLink to this definition
A
Lookupis a generic class to implement lookups. A lookup is a query expression with a left-hand side,lhs; a right-hand side,rhs; and alookup_namethat is used to produce a boolean comparison betweenlhsandrhssuch aslhs in rhsorlhs > rhs.The primary notation to use a lookup in an expression is
<lhs>__<lookup_name>=<rhs>. Lookups can also be used directly inQuerySetfilters:Book.objects.filter(LessThan(F("word_count"), 7500))…or annotations:
Book.objects.annotate(is_short_story=LessThan(F("word_count"), 7500))- lhsLink to this definition
The left-hand side - what is being looked up. The object typically follows the Query Expression API. It may also be a plain value.
- rhsLink to this definition
The right-hand side - what
lhsis being compared against. It can be a plain value, or something that compiles into SQL, typically anF()object or aQuerySet.
- lookup_nameLink to this definition
The name of this lookup, used to identify it on parsing query expressions. It cannot contain the string
"__".
- prepare_rhsLink to this definition
Defaults to
True. Whenrhsis a plain value,prepare_rhsdetermines whether it should be prepared for use as a parameter in a query. In order to do so,lhs.output_field.get_prep_value()is called if defined, orrhsis wrapped inValue()otherwise.
- process_lhs(compiler, connection, lhs=None)Link to this definition
Returns a tuple
(lhs_string, lhs_params), as returned bycompiler.compile(lhs). This method can be overridden to tune how thelhsis processed.compileris anSQLCompilerobject, to be used likecompiler.compile(lhs)for compilinglhs. Theconnectioncan be used for compiling vendor specific SQL. Iflhsis notNone, use it as the processedlhsinstead ofself.lhs.
- process_rhs(compiler, connection)Link to this definition
Behaves the same way as
process_lhs(), for the right-hand side.