Lookup

class model_values.Lookup[source]

Mixin for field lookups.

Note

Spatial lookups require gis to be enabled.

__ge__(value)

gte

__gt__(value)

gt

__le__(value)

lte

__lshift__(value)

left

__lt__(value)

lt

__ne__(value)

ne

__rshift__(value)

right

above(value)

strictly_above

below(value)

strictly_below

contained(value)
contains(value, properly=False, bb=False)[source]

Return whether field contains the value. Options apply only to geom fields.

Parameters:
  • properlycontains_properly
  • bb – bounding box, bbcontains
coveredby(value)
covers(value)
crosses(value)
disjoint(value)
endswith(value)
equals(value)
icontains(value)
iendswith(value)
iexact(value)
intersects(value)
iregex(value)
is_valid

Whether field isvalid.

isin(value)

in

istartswith(value)
left(value)
overlaps(geom, position='', bb=False)[source]

Return whether field overlaps with geometry .

Parameters:
  • positionoverlaps_{left, right, above, below}
  • bb – bounding box, bboverlaps
range(*values)[source]
regex(value)
relate(*values)[source]
right(value)
startswith(value)
touches(value)
within(geom, distance=None)[source]

Return whether field is within geometry.

Parameters:distancedwithin

F

class model_values.F(name)[source]

Bases: django.db.models.expressions.F, model_values.Lookup

Create F, Q, and Func objects with expressions.

F creation supported as attributes: F.user == F('user'), F.user.created == F('user__created').

Q lookups supported as methods or operators: F.text.iexact(...) == Q(text__iexact=...), F.user.created >= ... == Q(user__created__gte=...).

Func objects also supported as methods: F.user.created.min() == Min('user__created').

Note

Since attributes are used for constructing F objects, there may be collisions between field names and methods. For example, name is a reserved attribute, but the usual constructor can still be used: F('name').

Note

See source for available spatial functions if gis is configured.

lookups

mapping of potentially registered lookups to transform functions

__abs__

Abs

__call__(*args, **extra) → django.db.models.expressions.Func[source]

Call self as a function.

__ceil__

Ceil

__eq__(value, lookup: str = '') → django.db.models.query_utils.Q[source]

Return Q object with lookup.

__floor__

Floor

__getattr__(name: str) → model_values.F[source]

Return new F object with chained attribute.

__getitem__(slc: slice) → django.db.models.expressions.Func[source]

Return field Substr or Right.

__hash__()[source]

Return hash(self).

__mod__

Mod

__ne__(value) → django.db.models.query_utils.Q[source]

Allow __ne=None lookup without custom queryset.

__pow__

Power

__reversed__

Reverse

__round__

Round

cast

Coerce an expression to a new field type.

coalesce

Return, from left to right, the first non-null expression.

concat

Concatenate text fields together. Backends that result in an entire null expression when any arguments are null will wrap each argument in coalesce functions to ensure a non-null result.

count()[source]

Return Count with optional field.

cume_dist

CumeDist

dense_rank

DenseRank

extract

Extract

find(sub, **extra) → django.db.models.expressions.Expression[source]

Return StrIndex with str.find semantics.

first_value

FirstValue

greatest

Return the maximum expression.

If any expression is null the return value is database-specific: On PostgreSQL, the maximum not-null expression is returned. On MySQL, Oracle, and SQLite, if any expression is null, null is returned.

lag

Lag

last_value

LastValue

lead

Lead

least

Return the minimum expression.

If any expression is null the return value is database-specific: On PostgreSQL, return the minimum not-null expression. On MySQL, Oracle, and SQLite, if any expression is null, return null.

ljust(width: int, fill=' ', **extra) → django.db.models.expressions.Func[source]

Return LPad with wrapped values.

log(base=2.718281828459045, **extra) → django.db.models.expressions.Func[source]

Return Log, by default Ln.

lstrip

LTrim

max

Max

mean

Avg

min

Min

now

alias of django.db.models.functions.datetime.Now

nth_value

NthValue

ntile

alias of django.db.models.functions.window.Ntile

nullif

NullIf

percent_rank

PercentRank

rank

Rank

repeat

Repeat

replace(old, new='', **extra) → django.db.models.expressions.Func[source]

Return Replace with wrapped values.

rjust(width: int, fill=' ', **extra) → django.db.models.expressions.Func[source]

Return RPad with wrapped values.

row_number

RowNumber

rstrip

RTrim

sha1

SHA1

sha224

SHA224

sha256

SHA256

sha384

SHA384

sha512

SHA512

std

StdDev

strip

Trim

sum

Sum

trunc

Trunc

var

Variance

QuerySet

class model_values.QuerySet(model=None, query=None, using=None, hints=None)[source]

Bases: django.db.models.query.QuerySet, model_values.Lookup

Note

See source for available aggregate spatial functions if gis is configured.

__add__(value)

add

__contains__(value)[source]

Return whether value is present using exists.

__eq__(value, lookup: str = '') → model_values.QuerySet[source]

Return QuerySet filtered by comparison to given value.

__getitem__(key)[source]

Allow column access by field names, expressions, or F objects.

qs[field] returns flat values_list

qs[field, ...] returns tupled values_list

qs[Q_obj] provisionally returns filtered QuerySet

__iter__()[source]

Iteration extended to support groupby().

__mod__(value)

mod

__mul__(value)

mul

__pow__(value)

pow

__setitem__(key, value)[source]

Update a single column.

__sub__(value)

sub

__truediv__(value)

truediv

annotate(*args, **kwargs) → model_values.QuerySet[source]

Annotate extended to also handle mapping values, as a Case expression.

Parameters:kwargsfield={Q_obj: value, ...}, ...

As a provisional feature, an optional default key may be specified.

change(defaults: Mapping[KT, VT_co] = {}, **kwargs) → int[source]

Update and return number of rows that actually changed.

For triggering on-change logic without fetching first.

if qs.change(status=...): status actually changed

qs.change({'last_modified': now}, status=...) last_modified only updated if status updated

Parameters:defaults – optional mapping which will be updated conditionally, as with update_or_create.
changed(**kwargs) → dict[source]

Return first mapping of fields and values which differ in the db.

Also efficient enough to be used in boolean contexts, instead of exists.

exists(count: int = 1) → bool[source]

Return whether there are at least the specified number of rows.

groupby(*fields, **annotations) → model_values.QuerySet[source]

Return a grouped QuerySet.

The queryset is iterable in the same manner as itertools.groupby. Additionally the reduce() functions will return annotated querysets.

items(*fields, **annotations) → model_values.QuerySet[source]

Return annotated values_list.

max()

Max

mean()

Avg

min()

Min

reduce(*funcs)[source]

Return aggregated values, or an annotated QuerySet if groupby() is in use.

Parameters:funcs – aggregation function classes
sort_values(reverse=False) → model_values.QuerySet[source]

Return QuerySet ordered by selected values.

std()

StdDev

sum()

Sum

update(**kwargs) → int[source]

Update extended to also handle mapping values, as a Case expression.

Parameters:kwargsfield={Q_obj: value, ...}, ...
value_counts(alias: str = 'count') → model_values.QuerySet[source]

Return annotated value counts.

var()

Variance

Manager

class model_values.Manager[source]

Bases: django.db.models.manager.Manager

__contains__(pk)[source]

Return whether primary key is present using exists.

__delitem__(pk)[source]

Delete row with primary key.

__getitem__(pk) → model_values.QuerySet[source]

Return QuerySet which matches primary key.

To encourage direct db access, instead of always using get and save.

bulk_change(field, data: Mapping[KT, VT_co], key: str = 'pk', conditional=False, **kwargs) → int[source]

Update changed rows with a minimal number of queries, by inverting the data to use pk__in.

Parameters:
  • field – value column
  • data{pk: value, ...}
  • key – unique key column
  • conditional – execute select query and single conditional update; may be more efficient if the percentage of changed rows is relatively small
  • kwargs – additional fields to be updated
bulk_changed(field, data: Mapping[KT, VT_co], key: str = 'pk') → dict[source]

Return mapping of values which differ in the db.

Parameters:
  • field – value column
  • data{pk: value, ...}
  • key – unique key column
get_queryset()[source]

Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager.

upsert(defaults: Mapping[KT, VT_co] = {}, **kwargs) → Union[int, django.db.models.base.Model][source]

Update or insert returning number of rows or created object.

Faster and safer than update_or_create. Supports combined expression updates by assuming the identity element on insert: F(...) + 1.

Parameters:defaults – optional mapping which will be updated, as with update_or_create.

Case

class model_values.Case(conds, default=None, **extra)[source]

Bases: django.db.models.expressions.Case

Case expression from mapping of when conditionals.

Parameters:
  • conds{Q_obj: value, ...}
  • default – optional default value or F object
  • output_field – optional field defaults to registered types
types = {<class 'str'>: <class 'django.db.models.fields.CharField'>, <class 'int'>: <class 'django.db.models.fields.IntegerField'>, <class 'float'>: <class 'django.db.models.fields.FloatField'>, <class 'bool'>: <class 'django.db.models.fields.BooleanField'>}

mapping of types to output fields

classproperty

class model_values.classproperty[source]

Bases: property

A property bound to a class.

EnumField

model_values.EnumField(enum, display: Callable = None, **options) → django.db.models.fields.Field[source]

Return a CharField or IntegerField with choices from given enum.

By default, enum names and values are used as db values and display labels respectively, returning a CharField with computed max_length.

Parameters:display – optional callable to transform enum names to display labels, thereby using enum values as db values and also supporting integers.