Python django.db.models.fields.DateField() Examples

The following are 27 code examples of django.db.models.fields.DateField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.models.fields , or try the search function .
Example #1
Source File: djpeewee.py    From Quiver-alfred with MIT License 6 votes vote down vote up
def get_django_field_map(self):
        from django.db.models import fields as djf
        return [
            (djf.AutoField, PrimaryKeyField),
            (djf.BigIntegerField, BigIntegerField),
            # (djf.BinaryField, BlobField),
            (djf.BooleanField, BooleanField),
            (djf.CharField, CharField),
            (djf.DateTimeField, DateTimeField),  # Extends DateField.
            (djf.DateField, DateField),
            (djf.DecimalField, DecimalField),
            (djf.FilePathField, CharField),
            (djf.FloatField, FloatField),
            (djf.IntegerField, IntegerField),
            (djf.NullBooleanField, partial(BooleanField, null=True)),
            (djf.TextField, TextField),
            (djf.TimeField, TimeField),
            (djf.related.ForeignKey, ForeignKeyField),
        ] 
Example #2
Source File: applications.py    From mitoc-trips with GNU General Public License v3.0 6 votes vote down vote up
def get_feedback(self):
        """ Return all feedback for the participant.

        Activity chairs see the complete history of feedback (without the normal
        "clean slate" period). The only exception is that activity chairs cannot
        see their own feedback.
        """
        return (
            models.Feedback.everything.filter(participant=self.object.participant)
            .exclude(participant=self.chair)
            .select_related('leader', 'trip')
            .prefetch_related('leader__leaderrating_set')
            .annotate(
                display_date=Least('trip__trip_date', Cast('time_created', DateField()))
            )
            .order_by('-display_date')
        ) 
Example #3
Source File: build_search_filters.py    From openprescribing with MIT License 6 votes vote down vote up
def _build_search_filter(cls, field_name):
    if field_name == "bnf_code":
        return _build_search_filter_bnf_code_prefox()

    field = cls._meta.get_field(field_name)
    builder = {
        ForeignKey: _build_search_filter_fk,
        ManyToOneRel: _build_search_filter_rev_fk,
        OneToOneRel: _build_search_filter_rev_fk,
        fields.CharField: _build_search_filter_char,
        fields.DateField: _build_search_filter_date,
        fields.BooleanField: _build_search_filter_boolean,
        fields.DecimalField: _build_search_filter_decimal,
    }[type(field)]
    search_filter = builder(field)
    search_filter["id"] = field_name
    return search_filter 
Example #4
Source File: bigquery.py    From openprescribing with MIT License 6 votes vote down vote up
def build_schema_from_model(model):
    field_mappings = {
        model_fields.BigIntegerField: "INTEGER",
        model_fields.CharField: "STRING",
        model_fields.DateField: "DATE",
        model_fields.FloatField: "FLOAT",
        model_fields.DecimalField: "NUMERIC",
        model_fields.IntegerField: "INTEGER",
        model_fields.BooleanField: "BOOLEAN",
        model_fields.NullBooleanField: "BOOLEAN",
        model_fields.TextField: "STRING",
        related_fields.ForeignKey: "INTEGER",
        related_fields.OneToOneField: "INTEGER",
    }

    fields = [
        (f.name, field_mappings[type(f)])
        for f in model._meta.fields
        if not f.auto_created
    ]

    return build_schema(*fields) 
Example #5
Source File: operations.py    From bioforum with MIT License 6 votes vote down vote up
def get_db_converters(self, expression):
        converters = super().get_db_converters(expression)
        internal_type = expression.output_field.get_internal_type()
        if internal_type == 'DateTimeField':
            converters.append(self.convert_datetimefield_value)
        elif internal_type == 'DateField':
            converters.append(self.convert_datefield_value)
        elif internal_type == 'TimeField':
            converters.append(self.convert_timefield_value)
        # Converter for Col is added with Database.register_converter()
        # in base.py.
        elif internal_type == 'DecimalField' and not isinstance(expression, Col):
            converters.append(self.convert_decimalfield_value)
        elif internal_type == 'UUIDField':
            converters.append(self.convert_uuidfield_value)
        elif internal_type in ('NullBooleanField', 'BooleanField'):
            converters.append(self.convert_booleanfield_value)
        return converters 
Example #6
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def get_db_converters(self, expression):
        converters = super().get_db_converters(expression)
        internal_type = expression.output_field.get_internal_type()
        if internal_type == 'DateTimeField':
            converters.append(self.convert_datetimefield_value)
        elif internal_type == 'DateField':
            converters.append(self.convert_datefield_value)
        elif internal_type == 'TimeField':
            converters.append(self.convert_timefield_value)
        elif internal_type == 'DecimalField':
            converters.append(self.get_decimalfield_converter(expression))
        elif internal_type == 'UUIDField':
            converters.append(self.convert_uuidfield_value)
        elif internal_type in ('NullBooleanField', 'BooleanField'):
            converters.append(self.convert_booleanfield_value)
        return converters 
Example #7
Source File: operations.py    From python with Apache License 2.0 6 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                    if isinstance(output_field, bad_fields):
                        raise NotImplementedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        )
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass 
Example #8
Source File: operations.py    From python with Apache License 2.0 6 votes vote down vote up
def get_db_converters(self, expression):
        converters = super(DatabaseOperations, self).get_db_converters(expression)
        internal_type = expression.output_field.get_internal_type()
        if internal_type == 'DateTimeField':
            converters.append(self.convert_datetimefield_value)
        elif internal_type == 'DateField':
            converters.append(self.convert_datefield_value)
        elif internal_type == 'TimeField':
            converters.append(self.convert_timefield_value)
        elif internal_type == 'DecimalField':
            converters.append(self.convert_decimalfield_value)
        elif internal_type == 'UUIDField':
            converters.append(self.convert_uuidfield_value)
        elif internal_type in ('NullBooleanField', 'BooleanField'):
            converters.append(self.convert_booleanfield_value)
        return converters 
Example #9
Source File: operations.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                    if isinstance(output_field, bad_fields):
                        raise NotImplementedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        )
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass 
Example #10
Source File: operations.py    From python2017 with MIT License 6 votes vote down vote up
def get_db_converters(self, expression):
        converters = super(DatabaseOperations, self).get_db_converters(expression)
        internal_type = expression.output_field.get_internal_type()
        if internal_type == 'DateTimeField':
            converters.append(self.convert_datetimefield_value)
        elif internal_type == 'DateField':
            converters.append(self.convert_datefield_value)
        elif internal_type == 'TimeField':
            converters.append(self.convert_timefield_value)
        elif internal_type == 'DecimalField':
            converters.append(self.convert_decimalfield_value)
        elif internal_type == 'UUIDField':
            converters.append(self.convert_uuidfield_value)
        elif internal_type in ('NullBooleanField', 'BooleanField'):
            converters.append(self.convert_booleanfield_value)
        return converters 
Example #11
Source File: operations.py    From python2017 with MIT License 6 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                    if isinstance(output_field, bad_fields):
                        raise NotImplementedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        )
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass 
Example #12
Source File: models.py    From django-stubs with MIT License 5 votes vote down vote up
def run_with_model_cls(self, model_cls: Type[Model]) -> None:
        # get_FOO_display for choices
        for field in self.django_context.get_model_fields(model_cls):
            if field.choices:
                info = self.lookup_typeinfo_or_incomplete_defn_error('builtins.str')
                return_type = Instance(info, [])
                common.add_method(self.ctx,
                                  name='get_{}_display'.format(field.attname),
                                  args=[],
                                  return_type=return_type)

        # get_next_by, get_previous_by for Date, DateTime
        for field in self.django_context.get_model_fields(model_cls):
            if isinstance(field, (DateField, DateTimeField)) and not field.null:
                return_type = Instance(self.model_classdef.info, [])
                common.add_method(self.ctx,
                                  name='get_next_by_{}'.format(field.attname),
                                  args=[Argument(Var('kwargs', AnyType(TypeOfAny.explicit)),
                                                 AnyType(TypeOfAny.explicit),
                                                 initializer=None,
                                                 kind=ARG_STAR2)],
                                  return_type=return_type)
                common.add_method(self.ctx,
                                  name='get_previous_by_{}'.format(field.attname),
                                  args=[Argument(Var('kwargs', AnyType(TypeOfAny.explicit)),
                                                 AnyType(TypeOfAny.explicit),
                                                 initializer=None,
                                                 kind=ARG_STAR2)],
                                  return_type=return_type) 
Example #13
Source File: build_search_query.py    From openprescribing with MIT License 5 votes vote down vote up
def _build_lookup_key(cls, field_name, operator):
    field = cls._meta.get_field(field_name)
    builder = {
        ForeignKey: _build_lookup_fk,
        ManyToOneRel: _build_lookup_rev_fk,
        OneToOneRel: _build_lookup_rev_fk,
        fields.CharField: _build_lookup_char,
        fields.DateField: _build_lookup_date,
        fields.BooleanField: _build_lookup_boolean,
        fields.DecimalField: _build_lookup_decimal,
    }[type(field)]
    return builder(cls, field_name, operator) 
Example #14
Source File: player.py    From hawthorne with GNU Lesser General Public License v3.0 5 votes vote down vote up
def detailed_log_entries(request, u, date, page, *args, **kwargs):
  pages = ServerChat.objects.filter(user=u)\
                            .annotate(created_date=Cast('created_at', DateField()))\
                            .values('created_date')\
                            .distinct()\
                            .order_by('-created_date')

  date = pages[date - 1]['created_date']
  logs = ServerChat.objects.annotate(created_date=Cast('created_at', DateField()))\
                           .filter(user=u, created_date=date).order_by('created_at')

  return renderer(request, 'components/players/detailed/logs/entry.pug', logs, page) 
Example #15
Source File: player.py    From hawthorne with GNU Lesser General Public License v3.0 5 votes vote down vote up
def detailed_log_date(request, u, date, *args, **kwargs):
  pages = ServerChat.objects.filter(user=u)\
                            .annotate(created_date=Cast('created_at', DateField()))\
                            .values('created_date')\
                            .distinct()\
                            .order_by('-created_date')

  return HttpResponse(date_format(pages[date - 1]['created_date'],
                                  format='SHORT_DATE_FORMAT',
                                  use_l10n=True)) 
Example #16
Source File: player.py    From hawthorne with GNU Lesser General Public License v3.0 5 votes vote down vote up
def detailed_log(request, u, *args, **kwargs):
  c = request.POST.get("page", 1)
  pages = ServerChat.objects.filter(user=u)\
                            .annotate(created_date=Cast('created_at', DateField()))\
                            .values('created_date')\
                            .distinct()\
                            .order_by('-created_date')\
                            .count()

  return render(request, 'components/players/detailed/logs/wrapper.pug', {'pages': pages,
                                                                          'current': c}) 
Example #17
Source File: expressions.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
        copy = self.copy()
        copy.col = query.resolve_ref(self.lookup, allow_joins, reuse, summarize)
        field = copy.col.output_field
        assert isinstance(field, fields.DateField), "%r isn't a DateField." % field.name
        if settings.USE_TZ:
            assert not isinstance(field, fields.DateTimeField), (
                "%r is a DateTimeField, not a DateField." % field.name
            )
        return copy 
Example #18
Source File: expressions.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __init__(self, lookup, lookup_type):
        super(Date, self).__init__(output_field=fields.DateField())
        self.lookup = lookup
        self.col = None
        self.lookup_type = lookup_type 
Example #19
Source File: operations.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_db_converters(self, expression):
        converters = super(DatabaseOperations, self).get_db_converters(expression)
        internal_type = expression.output_field.get_internal_type()
        if internal_type == 'DateTimeField':
            converters.append(self.convert_datetimefield_value)
        elif internal_type == 'DateField':
            converters.append(self.convert_datefield_value)
        elif internal_type == 'TimeField':
            converters.append(self.convert_timefield_value)
        elif internal_type == 'DecimalField':
            converters.append(self.convert_decimalfield_value)
        elif internal_type == 'UUIDField':
            converters.append(self.convert_uuidfield_value)
        return converters 
Example #20
Source File: subqueries.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def add_date_select(self, field_name, lookup_type, order='ASC'):
        """
        Converts the query into a date extraction query.
        """
        try:
            result = self.setup_joins(
                field_name.split(LOOKUP_SEP),
                self.get_meta(),
                self.get_initial_alias(),
                False
            )
        except FieldError:
            raise FieldDoesNotExist("%s has no field named '%s'" % (
                self.model._meta.object_name, field_name
            ))
        field = result[0]
        assert isinstance(field, DateField), "%r isn't a DateField." \
                % field.name
        alias = result[3][-1]
        select = Date((alias, field.column), lookup_type)
        self.clear_select_clause()
        self.select, self.select_fields = [select], [None]
        self.distinct = True
        self.order_by = order == 'ASC' and [1] or [-1]

        if field.null:
            self.add_filter(("%s__isnull" % field_name, False)) 
Example #21
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass
                else:
                    if isinstance(output_field, bad_fields):
                        raise utils.NotSupportedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        ) 
Example #22
Source File: layer_selection.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def sql_map_lambda(self, query_set):
        field_to_table_lookup = map_to_dict(lambda tup: [tup[1], tup[0]], query_set.query.select)
        def sql_map(path):
            """
                Like field_map, but instead produces a sql version of the mapping.
                Since our export functionality sends sql to ogr, we need to handle
                all the formatting in the sql. We can do this by overriding the normal
                select value with a function (e.g. select updated_date becomes select format(update_data).
                In order to do this we create an extra clause for the Django QuerySet since it sadly
                doesn't have a built-in ability to decorate selections with functions
            :param path:
            :param field_class_path:
            :return: An array with two values, the path and the mapping. If no mapping
            is needed, an array with [path, path] is returned. This way the path is used as an extra
            value and the column order is preserved. Django nonsensically puts the extra fields before
            the normal fields, even if their names match. Apparently they didn't considered the situation
            of replacing a normal column select with a formatted column select, or they don't expect
            raw sql to be used.
            """

            full_column_name = '%s.%s' % (field_to_table_lookup.get(path), path.split('__')[-1]) if field_to_table_lookup.get(path) else path
            field_class_path = self.result_map.field_lookup.get(path)
            if not field_class_path:
                return None
            resolved_field_class = resolve_module_attr(field_class_path)
            if resolved_field_class and issubclass(resolved_field_class, DateField):
                # Format the date to match our prefered style (gotta love SQL :< )
                return [path,
                        "to_char({0}, 'YYYY-MM-DD') || 'T' || to_char({0}, 'HH:MI:SS') || to_char(extract(TIMEZONE_HOUR FROM {0}), 'fm00') || ':' || to_char(extract(TIMEZONE_MINUTE FROM {0}), 'fm00')".format(full_column_name)]
            return None
        return sql_map 
Example #23
Source File: operations.py    From bioforum with MIT License 5 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass
                else:
                    if isinstance(output_field, bad_fields):
                        raise NotImplementedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        ) 
Example #24
Source File: expressions.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
        copy = self.copy()
        copy.col = query.resolve_ref(self.lookup, allow_joins, reuse, summarize)
        field = copy.col.output_field
        assert isinstance(field, fields.DateField), "%r isn't a DateField." % field.name
        if settings.USE_TZ:
            assert not isinstance(field, fields.DateTimeField), (
                "%r is a DateTimeField, not a DateField." % field.name
            )
        return copy 
Example #25
Source File: expressions.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, lookup, lookup_type):
        super(Date, self).__init__(output_field=fields.DateField())
        self.lookup = lookup
        self.col = None
        self.lookup_type = lookup_type 
Example #26
Source File: operations.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_db_converters(self, expression):
        converters = super(DatabaseOperations, self).get_db_converters(expression)
        internal_type = expression.output_field.get_internal_type()
        if internal_type == 'DateTimeField':
            converters.append(self.convert_datetimefield_value)
        elif internal_type == 'DateField':
            converters.append(self.convert_datefield_value)
        elif internal_type == 'TimeField':
            converters.append(self.convert_timefield_value)
        elif internal_type == 'DecimalField':
            converters.append(self.convert_decimalfield_value)
        elif internal_type == 'UUIDField':
            converters.append(self.convert_uuidfield_value)
        return converters 
Example #27
Source File: operations.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            try:
                output_field = expression.input_field.output_field
                if isinstance(output_field, bad_fields):
                    raise NotImplementedError(
                        'You cannot use Sum, Avg, StdDev and Variance aggregations '
                        'on date/time fields in sqlite3 '
                        'since date/time is saved as text.')
            except FieldError:
                # not every sub-expression has an output_field which is fine to
                # ignore
                pass