class TruncWeek

from django.db.models.functions.datetime import TruncWeek
Truncate to midnight on the Monday of the week.

Ancestors (MRO)

  1. builtins.object
  2. django.db.models.expressions.Combinable
  3. django.db.models.expressions.BaseExpression
  4. django.db.models.expressions.Expression
  5. django.db.models.expressions.SQLiteNumericMixin
  6. django.db.models.expressions.Func
  7. django.db.models.query_utils.RegisterLookupMixin
  8. django.db.models.lookups.Transform
  9. django.db.models.functions.datetime.TimezoneMixin
  10. django.db.models.functions.datetime.TruncBase
  11. django.db.models.functions.datetime.TruncWeek
AttributeValueDefined in
def allowed_default(self)
django.db.models.expressions.Func
def as_sql(self, compiler, connection)
django.db.models.functions.datetime.TruncBase
django.db.models.functions.datetime.TruncBase
Responsible for returning a (sql, [params]) tuple to be included
in the current query.

Different backends can provide their own implementation, by
providing an `as_{vendor}` method and patching the Expression:

```
def override_as_sql(self, compiler, connection):
    # custom logic
    return super().as_sql(compiler, connection)
setattr(Expression, 'as_' + connection.vendor, override_as_sql)
```

Arguments:
 * compiler: the query compiler responsible for generating the query.
   Must have a compile method, returning a (sql, [params]) tuple.
   Calling compiler(value) will return a quoted `value`.

 * connection: the database connection used for the current query.

Return: (sql, params)
  Where `sql` is a string containing ordered sql parameters to be
  replaced with the elements of the list `params`.
    def as_sql(self, compiler, connection):
        sql, params = compiler.compile(self.lhs)
        tzname = None
        if isinstance(self.lhs.output_field, DateTimeField):
            tzname = self.get_tzname()
        elif self.tzinfo is not None:
            raise ValueError("tzinfo can only be used with DateTimeField.")
        if isinstance(self.output_field, DateTimeField):
            sql, params = connection.ops.datetime_trunc_sql(
                self.kind, sql, tuple(params), tzname
            )
        elif isinstance(self.output_field, DateField):
            sql, params = connection.ops.date_trunc_sql(
                self.kind, sql, tuple(params), tzname
            )
        elif isinstance(self.output_field, TimeField):
            sql, params = connection.ops.time_trunc_sql(
                self.kind, sql, tuple(params), tzname
            )
        else:
            raise ValueError(
                "Trunc only valid on DateField, TimeField, or DateTimeField."
            )
        return sql, params
django.db.models.expressions.Func
Responsible for returning a (sql, [params]) tuple to be included
in the current query.

Different backends can provide their own implementation, by
providing an `as_{vendor}` method and patching the Expression:

```
def override_as_sql(self, compiler, connection):
    # custom logic
    return super().as_sql(compiler, connection)
setattr(Expression, 'as_' + connection.vendor, override_as_sql)
```

Arguments:
 * compiler: the query compiler responsible for generating the query.
   Must have a compile method, returning a (sql, [params]) tuple.
   Calling compiler(value) will return a quoted `value`.

 * connection: the database connection used for the current query.

Return: (sql, params)
  Where `sql` is a string containing ordered sql parameters to be
  replaced with the elements of the list `params`.
    def as_sql(
        self,
        compiler,
        connection,
        function=None,
        template=None,
        arg_joiner=None,
        **extra_context,
    ):
        connection.ops.check_expression_support(self)
        sql_parts = []
        params = []
        for arg in self.source_expressions:
            try:
                arg_sql, arg_params = compiler.compile(arg)
            except EmptyResultSet:
                empty_result_set_value = getattr(
                    arg, "empty_result_set_value", NotImplemented
                )
                if empty_result_set_value is NotImplemented:
                    raise
                arg_sql, arg_params = compiler.compile(Value(empty_result_set_value))
            except FullResultSet:
                arg_sql, arg_params = compiler.compile(Value(True))
            sql_parts.append(arg_sql)
            params.extend(arg_params)
        data = {**self.extra, **extra_context}
        # Use the first supplied value in this order: the parameter to this
        # method, a value supplied in __init__()'s **extra (the value in
        # `data`), or the value defined on the class.
        if function is not None:
            data["function"] = function
        else:
            data.setdefault("function", self.function)
        template = template or data.get("template", self.template)
        arg_joiner = arg_joiner or data.get("arg_joiner", self.arg_joiner)
        data["expressions"] = data["field"] = arg_joiner.join(sql_parts)
        return template % data, params
django.db.models.expressions.BaseExpression
Responsible for returning a (sql, [params]) tuple to be included
in the current query.

Different backends can provide their own implementation, by
providing an `as_{vendor}` method and patching the Expression:

```
def override_as_sql(self, compiler, connection):
    # custom logic
    return super().as_sql(compiler, connection)
setattr(Expression, 'as_' + connection.vendor, override_as_sql)
```

Arguments:
 * compiler: the query compiler responsible for generating the query.
   Must have a compile method, returning a (sql, [params]) tuple.
   Calling compiler(value) will return a quoted `value`.

 * connection: the database connection used for the current query.

Return: (sql, params)
  Where `sql` is a string containing ordered sql parameters to be
  replaced with the elements of the list `params`.
    def as_sql(self, compiler, connection):
        """
        Responsible for returning a (sql, [params]) tuple to be included
        in the current query.

        Different backends can provide their own implementation, by
        providing an `as_{vendor}` method and patching the Expression:

        ```
        def override_as_sql(self, compiler, connection):
            # custom logic
            return super().as_sql(compiler, connection)
        setattr(Expression, 'as_' + connection.vendor, override_as_sql)
        ```

        Arguments:
         * compiler: the query compiler responsible for generating the query.
           Must have a compile method, returning a (sql, [params]) tuple.
           Calling compiler(value) will return a quoted `value`.

         * connection: the database connection used for the current query.

        Return: (sql, params)
          Where `sql` is a string containing ordered sql parameters to be
          replaced with the elements of the list `params`.
        """
        raise NotImplementedError("Subclasses must implement as_sql()")
def as_sqlite(self, compiler, connection, **extra_context)
django.db.models.expressions.SQLiteNumericMixin
    def as_sqlite(self, compiler, connection, **extra_context):
        sql, params = self.as_sql(compiler, connection, **extra_context)
        try:
            if self.output_field.get_internal_type() == "DecimalField":
                sql = "(CAST(%s AS NUMERIC))" % sql
        except FieldError:
            pass
        return sql, params
def asc(self, **kwargs)
django.db.models.expressions.BaseExpression
    def asc(self, **kwargs):
        return OrderBy(self, **kwargs)
def bitand(self, other)
django.db.models.expressions.Combinable
    def bitand(self, other):
        return self._combine(other, self.BITAND, False)
def bitleftshift(self, other)
django.db.models.expressions.Combinable
    def bitleftshift(self, other):
        return self._combine(other, self.BITLEFTSHIFT, False)
def bitor(self, other)
django.db.models.expressions.Combinable
    def bitor(self, other):
        return self._combine(other, self.BITOR, False)
def bitrightshift(self, other)
django.db.models.expressions.Combinable
    def bitrightshift(self, other):
        return self._combine(other, self.BITRIGHTSHIFT, False)
def bitxor(self, other)
django.db.models.expressions.Combinable
    def bitxor(self, other):
        return self._combine(other, self.BITXOR, False)
def conditional(self)
django.db.models.expressions.BaseExpression
def contains_aggregate(self)
django.db.models.expressions.BaseExpression
def contains_column_references(self)
django.db.models.expressions.BaseExpression
def contains_over_clause(self)
django.db.models.expressions.BaseExpression
def contains_subquery(self)
django.db.models.expressions.BaseExpression
def convert_value(self, value, expression, connection)
django.db.models.functions.datetime.TruncBase
django.db.models.functions.datetime.TruncBase
Expressions provide their own converters because users have the option
of manually specifying the output_field which may be a different type
from the one the database returns.
    def convert_value(self, value, expression, connection):
        if isinstance(self.output_field, DateTimeField):
            if not settings.USE_TZ:
                pass
            elif value is not None:
                value = value.replace(tzinfo=None)
                value = timezone.make_aware(value, self.tzinfo)
            elif not connection.features.has_zoneinfo_database:
                raise ValueError(
                    "Database returned an invalid datetime value. Are time "
                    "zone definitions for your database installed?"
                )
        elif isinstance(value, datetime):
            if value is None:
                pass
            elif isinstance(self.output_field, DateField):
                value = value.date()
            elif isinstance(self.output_field, TimeField):
                value = value.time()
        return value
django.db.models.expressions.BaseExpression
Expressions provide their own converters because users have the option
of manually specifying the output_field which may be a different type
from the one the database returns.
def copy(self)
django.db.models.expressions.Func
django.db.models.expressions.Func
    def copy(self):
        copy = super().copy()
        copy.source_expressions = self.source_expressions[:]
        copy.extra = self.extra.copy()
        return copy
django.db.models.expressions.BaseExpression
    def copy(self):
        return copy.copy(self)
def deconstruct(obj)
django.db.models.expressions.Func
django.db.models.expressions.Func
Return a 3-tuple of class import path, positional arguments,
and keyword arguments.
        def deconstruct(obj):
            """
            Return a 3-tuple of class import path, positional arguments,
            and keyword arguments.
            """
            # Fallback version
            if path and type(obj) is klass:
                module_name, _, name = path.rpartition(".")
            else:
                module_name = obj.__module__
                name = obj.__class__.__name__
            # Make sure it's actually there and not an inner class
            module = import_module(module_name)
            if not hasattr(module, name):
                raise ValueError(
                    "Could not find object %s in %s.\n"
                    "Please note that you cannot serialize things like inner "
                    "classes. Please move the object into the main module "
                    "body to use migrations.\n"
                    "For more information, see "
                    "https://docs.djangoproject.com/en/%s/topics/migrations/"
                    "#serializing-values" % (name, module_name, get_docs_version())
                )
            return (
                (
                    path
                    if path and type(obj) is klass
                    else f"{obj.__class__.__module__}.{name}"
                ),
                obj._constructor_args[0],
                obj._constructor_args[1],
            )
django.db.models.expressions.Expression
Return a 3-tuple of class import path, positional arguments,
and keyword arguments.
        def deconstruct(obj):
            """
            Return a 3-tuple of class import path, positional arguments,
            and keyword arguments.
            """
            # Fallback version
            if path and type(obj) is klass:
                module_name, _, name = path.rpartition(".")
            else:
                module_name = obj.__module__
                name = obj.__class__.__name__
            # Make sure it's actually there and not an inner class
            module = import_module(module_name)
            if not hasattr(module, name):
                raise ValueError(
                    "Could not find object %s in %s.\n"
                    "Please note that you cannot serialize things like inner "
                    "classes. Please move the object into the main module "
                    "body to use migrations.\n"
                    "For more information, see "
                    "https://docs.djangoproject.com/en/%s/topics/migrations/"
                    "#serializing-values" % (name, module_name, get_docs_version())
                )
            return (
                (
                    path
                    if path and type(obj) is klass
                    else f"{obj.__class__.__module__}.{name}"
                ),
                obj._constructor_args[0],
                obj._constructor_args[1],
            )
def desc(self, **kwargs)
django.db.models.expressions.BaseExpression
    def desc(self, **kwargs):
        return OrderBy(self, descending=True, **kwargs)
def field(self)
django.db.models.expressions.BaseExpression
def flatten(self)
django.db.models.expressions.BaseExpression
Recursively yield this expression and all subexpressions, in
depth-first order.
    def flatten(self):
        """
        Recursively yield this expression and all subexpressions, in
        depth-first order.
        """
        yield self
        for expr in self.get_source_expressions():
            if expr:
                if hasattr(expr, "flatten"):
                    yield from expr.flatten()
                else:
                    yield expr
def get_bilateral_transforms(self)
django.db.models.lookups.Transform
    def get_bilateral_transforms(self):
        if hasattr(self.lhs, "get_bilateral_transforms"):
            bilateral_transforms = self.lhs.get_bilateral_transforms()
        else:
            bilateral_transforms = []
        if self.bilateral:
            bilateral_transforms.append(self.__class__)
        return bilateral_transforms
def get_class_lookups(self)
django.db.models.query_utils.RegisterLookupMixin
    @functools.cache
    def get_class_lookups(cls):
        class_lookups = [
            parent.__dict__.get("class_lookups", {}) for parent in inspect.getmro(cls)
        ]
        return cls.merge_dicts(class_lookups)
def get_db_converters(self, connection)
django.db.models.expressions.BaseExpression
    def get_db_converters(self, connection):
        return (
            []
            if self.convert_value is self._convert_value_noop
            else [self.convert_value]
        ) + self.output_field.get_db_converters(connection)
def get_group_by_cols(self)
django.db.models.expressions.BaseExpression
    def get_group_by_cols(self):
        if not self.contains_aggregate:
            return [self]
        cols = []
        for source in self.get_source_expressions():
            cols.extend(source.get_group_by_cols())
        return cols
def get_instance_lookups(self)
django.db.models.query_utils.RegisterLookupMixin
    def get_instance_lookups(self):
        class_lookups = self.get_class_lookups()
        if instance_lookups := getattr(self, "instance_lookups", None):
            return {**class_lookups, **instance_lookups}
        return class_lookups
def get_lookup(self, lookup_name)
django.db.models.query_utils.RegisterLookupMixin
django.db.models.query_utils.RegisterLookupMixin
    def get_lookup(self, lookup_name):
        from django.db.models.lookups import Lookup

        found = self._get_lookup(lookup_name)
        if found is None and hasattr(self, "output_field"):
            return self.output_field.get_lookup(lookup_name)
        if found is not None and not issubclass(found, Lookup):
            return None
        return found
django.db.models.expressions.BaseExpression
    def get_lookup(self, lookup):
        return self.output_field.get_lookup(lookup)
def get_refs(self)
django.db.models.expressions.BaseExpression
    def get_refs(self):
        refs = set()
        for expr in self.get_source_expressions():
            refs |= expr.get_refs()
        return refs
def get_source_expressions(self)
django.db.models.expressions.Func
django.db.models.expressions.Func
    def get_source_expressions(self):
        return self.source_expressions
django.db.models.expressions.BaseExpression
    def get_source_expressions(self):
        return []
def get_source_fields(self)
django.db.models.expressions.BaseExpression
Return the underlying field types used by this aggregate.
    def get_source_fields(self):
        """Return the underlying field types used by this aggregate."""
        return [e._output_field_or_none for e in self.get_source_expressions()]
def get_transform(self, lookup_name)
django.db.models.query_utils.RegisterLookupMixin
django.db.models.query_utils.RegisterLookupMixin
    def get_transform(self, lookup_name):
        from django.db.models.lookups import Transform

        found = self._get_lookup(lookup_name)
        if found is None and hasattr(self, "output_field"):
            return self.output_field.get_transform(lookup_name)
        if found is not None and not issubclass(found, Transform):
            return None
        return found
django.db.models.expressions.BaseExpression
    def get_transform(self, name):
        return self.output_field.get_transform(name)
def get_tzname(self)
django.db.models.functions.datetime.TimezoneMixin
    def get_tzname(self):
        # Timezone conversions must happen to the input datetime *before*
        # applying a function. 2015-12-31 23:00:00 -02:00 is stored in the
        # database as 2016-01-01 01:00:00 +00:00. Any results should be
        # based on the input datetime not the stored datetime.
        tzname = None
        if settings.USE_TZ:
            if self.tzinfo is None:
                tzname = timezone.get_current_timezone_name()
            else:
                tzname = timezone._get_timezone_name(self.tzinfo)
        return tzname
def identity(self)
django.db.models.expressions.Expression
def lhs(self)
django.db.models.lookups.Transform
def merge_dicts(dicts)
django.db.models.query_utils.RegisterLookupMixin
Merge dicts in reverse to preference the order of the original list. e.g.,
merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
    @staticmethod
    def merge_dicts(dicts):
        """
        Merge dicts in reverse to preference the order of the original list. e.g.,
        merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
        """
        merged = {}
        for d in reversed(dicts):
            merged.update(d)
        return merged
def output_field(self)
django.db.models.expressions.BaseExpression
Return the output type of this expressions.
def prefix_references(self, prefix)
django.db.models.expressions.BaseExpression
    def prefix_references(self, prefix):
        clone = self.copy()
        clone.set_source_expressions(
            [
                (
                    F(f"{prefix}{expr.name}")
                    if isinstance(expr, F)
                    else expr.prefix_references(prefix)
                )
                for expr in self.get_source_expressions()
            ]
        )
        return clone
def register_class_lookup(cls, lookup, lookup_name=None)
django.db.models.query_utils.RegisterLookupMixin
    def register_class_lookup(cls, lookup, lookup_name=None):
        if lookup_name is None:
            lookup_name = lookup.lookup_name
        if "class_lookups" not in cls.__dict__:
            cls.class_lookups = {}
        cls.class_lookups[lookup_name] = lookup
        cls._clear_cached_class_lookups()
        return lookup
def register_instance_lookup(self, lookup, lookup_name=None)
django.db.models.query_utils.RegisterLookupMixin
    def register_instance_lookup(self, lookup, lookup_name=None):
        if lookup_name is None:
            lookup_name = lookup.lookup_name
        if "instance_lookups" not in self.__dict__:
            self.instance_lookups = {}
        self.instance_lookups[lookup_name] = lookup
        return lookup
def relabeled_clone(self, change_map)
django.db.models.expressions.BaseExpression
    def relabeled_clone(self, change_map):
        clone = self.copy()
        clone.set_source_expressions(
            [
                e.relabeled_clone(change_map) if e is not None else None
                for e in self.get_source_expressions()
            ]
        )
        return clone
def replace_expressions(self, replacements)
django.db.models.expressions.BaseExpression
    def replace_expressions(self, replacements):
        if replacement := replacements.get(self):
            return replacement
        clone = self.copy()
        source_expressions = clone.get_source_expressions()
        clone.set_source_expressions(
            [
                expr.replace_expressions(replacements) if expr else None
                for expr in source_expressions
            ]
        )
        return clone
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False)
django.db.models.functions.datetime.TruncBase
django.db.models.functions.datetime.TruncBase
Provide the chance to do any preprocessing or validation before being
added to the query.

Arguments:
 * query: the backend query implementation
 * allow_joins: boolean allowing or denying use of joins
   in this query
 * reuse: a set of reusable joins for multijoins
 * summarize: a terminal aggregate clause
 * for_save: whether this expression about to be used in a save or update

Return: an Expression to be added to the query.
    def resolve_expression(
        self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
    ):
        copy = super().resolve_expression(
            query, allow_joins, reuse, summarize, for_save
        )
        field = copy.lhs.output_field
        # DateTimeField is a subclass of DateField so this works for both.
        if not isinstance(field, (DateField, TimeField)):
            raise TypeError(
                "%r isn't a DateField, TimeField, or DateTimeField." % field.name
            )
        # If self.output_field was None, then accessing the field will trigger
        # the resolver to assign it to self.lhs.output_field.
        if not isinstance(copy.output_field, (DateField, DateTimeField, TimeField)):
            raise ValueError(
                "output_field must be either DateField, TimeField, or DateTimeField"
            )
        # Passing dates or times to functions expecting datetimes is most
        # likely a mistake.
        class_output_field = (
            self.__class__.output_field
            if isinstance(self.__class__.output_field, Field)
            else None
        )
        output_field = class_output_field or copy.output_field
        has_explicit_output_field = (
            class_output_field or field.__class__ is not copy.output_field.__class__
        )
        if type(field) is DateField and (
            isinstance(output_field, DateTimeField)
            or copy.kind in ("hour", "minute", "second", "time")
        ):
            raise ValueError(
                "Cannot truncate DateField '%s' to %s."
                % (
                    field.name,
                    (
                        output_field.__class__.__name__
                        if has_explicit_output_field
                        else "DateTimeField"
                    ),
                )
            )
        elif isinstance(field, TimeField) and (
            isinstance(output_field, DateTimeField)
            or copy.kind in ("year", "quarter", "month", "week", "day", "date")
        ):
            raise ValueError(
                "Cannot truncate TimeField '%s' to %s."
                % (
                    field.name,
                    (
                        output_field.__class__.__name__
                        if has_explicit_output_field
                        else "DateTimeField"
                    ),
                )
            )
        return copy
django.db.models.expressions.Func
Provide the chance to do any preprocessing or validation before being
added to the query.

Arguments:
 * query: the backend query implementation
 * allow_joins: boolean allowing or denying use of joins
   in this query
 * reuse: a set of reusable joins for multijoins
 * summarize: a terminal aggregate clause
 * for_save: whether this expression about to be used in a save or update

Return: an Expression to be added to the query.
    def resolve_expression(
        self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
    ):
        c = self.copy()
        c.is_summary = summarize
        for pos, arg in enumerate(c.source_expressions):
            c.source_expressions[pos] = arg.resolve_expression(
                query, allow_joins, reuse, summarize, for_save
            )
        return c
django.db.models.expressions.BaseExpression
Provide the chance to do any preprocessing or validation before being
added to the query.

Arguments:
 * query: the backend query implementation
 * allow_joins: boolean allowing or denying use of joins
   in this query
 * reuse: a set of reusable joins for multijoins
 * summarize: a terminal aggregate clause
 * for_save: whether this expression about to be used in a save or update

Return: an Expression to be added to the query.
    def resolve_expression(
        self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
    ):
        """
        Provide the chance to do any preprocessing or validation before being
        added to the query.

        Arguments:
         * query: the backend query implementation
         * allow_joins: boolean allowing or denying use of joins
           in this query
         * reuse: a set of reusable joins for multijoins
         * summarize: a terminal aggregate clause
         * for_save: whether this expression about to be used in a save or update

        Return: an Expression to be added to the query.
        """
        c = self.copy()
        c.is_summary = summarize
        c.set_source_expressions(
            [
                (
                    expr.resolve_expression(query, allow_joins, reuse, summarize)
                    if expr
                    else None
                )
                for expr in c.get_source_expressions()
            ]
        )
        return c
def reverse_ordering(self)
django.db.models.expressions.BaseExpression
    def reverse_ordering(self):
        return self
def select_format(self, compiler, sql, params)
django.db.models.expressions.BaseExpression
Custom format for select clauses. For example, EXISTS expressions need
to be wrapped in CASE WHEN on Oracle.
    def select_format(self, compiler, sql, params):
        """
        Custom format for select clauses. For example, EXISTS expressions need
        to be wrapped in CASE WHEN on Oracle.
        """
        if hasattr(self.output_field, "select_format"):
            return self.output_field.select_format(compiler, sql, params)
        return sql, params
def set_source_expressions(self, exprs)
django.db.models.expressions.Func
django.db.models.expressions.Func
    def set_source_expressions(self, exprs):
        self.source_expressions = exprs
django.db.models.expressions.BaseExpression
    def set_source_expressions(self, exprs):
        assert not exprs