A field lookup tells Django how to compare a model field instead of using the default exact match. Append a double-underscore suffix to the query argument: `first_name__startswith="J"` finds names beginning with J, while `first_name="J"` searches for a name equal to J. section 4.4.2
Think of the suffix as the comparison operator in a database restriction. The same mechanism works across data types: use text lookups for strings and comparison lookups such as `__gte` for dates or numbers. section 4.4.2
Filter musicians by name or birth date
Use `Musician.objects.filter(first_name__startswith="J")` for first names beginning with J. Use `Musician.objects.filter(birth__gte=date(1945, 1, 1))` for musicians born on or after January 1, 1945. In a management command, command-line date strings must be converted to a datetime object before querying. section 4.4.2 section 9.3
Common field lookups include:
- `__contains` and `__icontains` match text containing a value, optionally ignoring case. section 4.4.2
- `__startswith` and `__istartswith` match text beginning with a value, optionally ignoring case. section 4.4.2
- `__endswith` matches text ending with a value. section 4.4.2
- `__gt`, `__gte`, `__lt`, and `__lte` express greater-than and less-than comparisons. section 4.4.2
- `__in` matches a field against any value in an iterable, such as `id__in=[1, 4, 6]`. section 4.4.2
Remember that lookup names are case-sensitive where the query specifies it. Do not add an asterisk to create starts-with behavior; use the appropriate lookup suffix. Management commands can combine multiple lookup-filtered arguments, such as first name, last name, and birth date. section 4.4.2 section 9.3
Table 4.1 Commonly used field look-ups
|
Field Look-up
|
Name
|
Description
|
|---|---|---|
__contains
|
Contains
|
Text field contains the given value
|
__icontains
|
Case-insensitive contains
|
Text field contains the given value, ignoring case
|
__gt
|
Greater than
|
Objects with a field greater than the given value
|
__gte
|
Greater than equal
|
Objects with a field greater than or equal to the given value
|
__in
|
In iterable
|
Objects with a field value matching one of the values given in an iterable. Example:
id__in=[1, 4, 6] matches objects with an ID field of 1, 4, or 6.
|
__lt
|
Lesser than
|
Objects with a field lesser than the given value
|
__lte
|
Lesser than equal
|
Objects with a field lesser than or equal to the given value
|
__startswith
|
Starts with
|
Text field starts with the given value
|
__istartswith
|
Case-insensitive starts with
|
Text field starts with the given value, ignoring case
|
__endswith
|
Ends with
|
Text field ends with the given value
|
__iendswith
|
Case-insensitive ends with
|
Text field ends with the given value, ignoring case
|
Use the lookup table as a compact reference when choosing a text, comparison, or membership restriction. section 4.4.2
