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

The following are 22 code examples of django.db.models.fields.DurationField(). 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: expressions.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def as_sql(self, compiler, connection):
        try:
            lhs_output = self.lhs.output_field
        except FieldError:
            lhs_output = None
        try:
            rhs_output = self.rhs.output_field
        except FieldError:
            rhs_output = None
        if (not connection.features.has_native_duration_field and
                ((lhs_output and lhs_output.get_internal_type() == 'DurationField')
                or (rhs_output and rhs_output.get_internal_type() == 'DurationField'))):
            return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)
        expressions = []
        expression_params = []
        sql, params = compiler.compile(self.lhs)
        expressions.append(sql)
        expression_params.extend(params)
        sql, params = compiler.compile(self.rhs)
        expressions.append(sql)
        expression_params.extend(params)
        # order of precedence
        expression_wrapper = '(%s)'
        sql = connection.ops.combine_expression(self.connector, expressions)
        return expression_wrapper % sql, expression_params 
Example #2
Source File: expressions.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def as_sql(self, compiler, connection):
        try:
            lhs_output = self.lhs.output_field
        except FieldError:
            lhs_output = None
        try:
            rhs_output = self.rhs.output_field
        except FieldError:
            rhs_output = None
        if (not connection.features.has_native_duration_field and
                ((lhs_output and lhs_output.get_internal_type() == 'DurationField')
                or (rhs_output and rhs_output.get_internal_type() == 'DurationField'))):
            return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)
        expressions = []
        expression_params = []
        sql, params = compiler.compile(self.lhs)
        expressions.append(sql)
        expression_params.extend(params)
        sql, params = compiler.compile(self.rhs)
        expressions.append(sql)
        expression_params.extend(params)
        # order of precedence
        expression_wrapper = '(%s)'
        sql = connection.ops.combine_expression(self.connector, expressions)
        return expression_wrapper % sql, expression_params 
Example #3
Source File: expressions.py    From python with Apache License 2.0 5 votes vote down vote up
def as_sql(self, compiler, connection):
        try:
            lhs_output = self.lhs.output_field
        except FieldError:
            lhs_output = None
        try:
            rhs_output = self.rhs.output_field
        except FieldError:
            rhs_output = None
        if (not connection.features.has_native_duration_field and
                ((lhs_output and lhs_output.get_internal_type() == 'DurationField') or
                 (rhs_output and rhs_output.get_internal_type() == 'DurationField'))):
            return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)
        if (lhs_output and rhs_output and self.connector == self.SUB and
            lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and
                lhs_output.get_internal_type() == rhs_output.get_internal_type()):
            return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection)
        expressions = []
        expression_params = []
        sql, params = compiler.compile(self.lhs)
        expressions.append(sql)
        expression_params.extend(params)
        sql, params = compiler.compile(self.rhs)
        expressions.append(sql)
        expression_params.extend(params)
        # order of precedence
        expression_wrapper = '(%s)'
        sql = connection.ops.combine_expression(self.connector, expressions)
        return expression_wrapper % sql, expression_params 
Example #4
Source File: expressions.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, lhs, rhs):
        super(TemporalSubtraction, self).__init__(lhs, self.SUB, rhs, output_field=fields.DurationField()) 
Example #5
Source File: expressions.py    From python2017 with MIT License 5 votes vote down vote up
def compile(self, side, compiler, connection):
        if not isinstance(side, DurationValue):
            try:
                output = side.output_field
            except FieldError:
                pass
            else:
                if output.get_internal_type() == 'DurationField':
                    sql, params = compiler.compile(side)
                    return connection.ops.format_for_duration_arithmetic(sql), params
        return compiler.compile(side) 
Example #6
Source File: expressions.py    From python2017 with MIT License 5 votes vote down vote up
def as_sql(self, compiler, connection):
        try:
            lhs_output = self.lhs.output_field
        except FieldError:
            lhs_output = None
        try:
            rhs_output = self.rhs.output_field
        except FieldError:
            rhs_output = None
        if (not connection.features.has_native_duration_field and
                ((lhs_output and lhs_output.get_internal_type() == 'DurationField') or
                 (rhs_output and rhs_output.get_internal_type() == 'DurationField'))):
            return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)
        if (lhs_output and rhs_output and self.connector == self.SUB and
            lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and
                lhs_output.get_internal_type() == rhs_output.get_internal_type()):
            return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection)
        expressions = []
        expression_params = []
        sql, params = compiler.compile(self.lhs)
        expressions.append(sql)
        expression_params.extend(params)
        sql, params = compiler.compile(self.rhs)
        expressions.append(sql)
        expression_params.extend(params)
        # order of precedence
        expression_wrapper = '(%s)'
        sql = connection.ops.combine_expression(self.connector, expressions)
        return expression_wrapper % sql, expression_params 
Example #7
Source File: expressions.py    From python2017 with MIT License 5 votes vote down vote up
def _combine(self, other, connector, reversed, node=None):
        if not hasattr(other, 'resolve_expression'):
            # everything must be resolvable to an expression
            if isinstance(other, datetime.timedelta):
                other = DurationValue(other, output_field=fields.DurationField())
            else:
                other = Value(other)

        if reversed:
            return CombinedExpression(other, connector, self)
        return CombinedExpression(self, connector, other)

    #############
    # OPERATORS #
    ############# 
Example #8
Source File: expressions.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def compile(self, side, compiler, connection):
        if not isinstance(side, DurationValue):
            try:
                output = side.output_field
            except FieldError:
                pass
            else:
                if output.get_internal_type() == 'DurationField':
                    sql, params = compiler.compile(side)
                    return connection.ops.format_for_duration_arithmetic(sql), params
        return compiler.compile(side) 
Example #9
Source File: expressions.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _combine(self, other, connector, reversed, node=None):
        if not hasattr(other, 'resolve_expression'):
            # everything must be resolvable to an expression
            if isinstance(other, datetime.timedelta):
                other = DurationValue(other, output_field=fields.DurationField())
            else:
                other = Value(other)

        if reversed:
            return CombinedExpression(other, connector, self)
        return CombinedExpression(self, connector, other)

    #############
    # OPERATORS #
    ############# 
Example #10
Source File: expressions.py    From python with Apache License 2.0 5 votes vote down vote up
def __init__(self, lhs, rhs):
        super(TemporalSubtraction, self).__init__(lhs, self.SUB, rhs, output_field=fields.DurationField()) 
Example #11
Source File: expressions.py    From python with Apache License 2.0 5 votes vote down vote up
def compile(self, side, compiler, connection):
        if not isinstance(side, DurationValue):
            try:
                output = side.output_field
            except FieldError:
                pass
            else:
                if output.get_internal_type() == 'DurationField':
                    sql, params = compiler.compile(side)
                    return connection.ops.format_for_duration_arithmetic(sql), params
        return compiler.compile(side) 
Example #12
Source File: expressions.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _combine(self, other, connector, reversed, node=None):
        if not hasattr(other, 'resolve_expression'):
            # everything must be resolvable to an expression
            if isinstance(other, datetime.timedelta):
                other = DurationValue(other, output_field=fields.DurationField())
            else:
                other = Value(other)

        if reversed:
            return CombinedExpression(other, connector, self)
        return CombinedExpression(self, connector, other)

    #############
    # OPERATORS #
    ############# 
Example #13
Source File: expressions.py    From python with Apache License 2.0 5 votes vote down vote up
def _combine(self, other, connector, reversed, node=None):
        if not hasattr(other, 'resolve_expression'):
            # everything must be resolvable to an expression
            if isinstance(other, datetime.timedelta):
                other = DurationValue(other, output_field=fields.DurationField())
            else:
                other = Value(other)

        if reversed:
            return CombinedExpression(other, connector, self)
        return CombinedExpression(self, connector, other)

    #############
    # OPERATORS #
    ############# 
Example #14
Source File: expressions.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def compile(self, side, compiler, connection):
        if not isinstance(side, DurationValue):
            try:
                output = side.output_field
            except FieldError:
                pass
            else:
                if output.get_internal_type() == 'DurationField':
                    sql, params = compiler.compile(side)
                    return connection.ops.format_for_duration_arithmetic(sql), params
        return compiler.compile(side) 
Example #15
Source File: expressions.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def as_sql(self, compiler, connection):
        try:
            lhs_output = self.lhs.output_field
        except FieldError:
            lhs_output = None
        try:
            rhs_output = self.rhs.output_field
        except FieldError:
            rhs_output = None
        if (not connection.features.has_native_duration_field and
                ((lhs_output and lhs_output.get_internal_type() == 'DurationField') or
                 (rhs_output and rhs_output.get_internal_type() == 'DurationField'))):
            return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)
        if (lhs_output and rhs_output and self.connector == self.SUB and
            lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and
                lhs_output.get_internal_type() == rhs_output.get_internal_type()):
            return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection)
        expressions = []
        expression_params = []
        sql, params = compiler.compile(self.lhs)
        expressions.append(sql)
        expression_params.extend(params)
        sql, params = compiler.compile(self.rhs)
        expressions.append(sql)
        expression_params.extend(params)
        # order of precedence
        expression_wrapper = '(%s)'
        sql = connection.ops.combine_expression(self.connector, expressions)
        return expression_wrapper % sql, expression_params 
Example #16
Source File: expressions.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def _combine(self, other, connector, reversed):
        if not hasattr(other, 'resolve_expression'):
            # everything must be resolvable to an expression
            if isinstance(other, datetime.timedelta):
                other = DurationValue(other, output_field=fields.DurationField())
            else:
                other = Value(other)

        if reversed:
            return CombinedExpression(other, connector, self)
        return CombinedExpression(self, connector, other)

    #############
    # OPERATORS #
    ############# 
Example #17
Source File: expressions.py    From bioforum with MIT License 5 votes vote down vote up
def compile(self, side, compiler, connection):
        if not isinstance(side, DurationValue):
            try:
                output = side.output_field
            except FieldError:
                pass
            else:
                if output.get_internal_type() == 'DurationField':
                    sql, params = compiler.compile(side)
                    return connection.ops.format_for_duration_arithmetic(sql), params
        return compiler.compile(side) 
Example #18
Source File: expressions.py    From bioforum with MIT License 5 votes vote down vote up
def as_sql(self, compiler, connection):
        try:
            lhs_output = self.lhs.output_field
        except FieldError:
            lhs_output = None
        try:
            rhs_output = self.rhs.output_field
        except FieldError:
            rhs_output = None
        if (not connection.features.has_native_duration_field and
                ((lhs_output and lhs_output.get_internal_type() == 'DurationField') or
                 (rhs_output and rhs_output.get_internal_type() == 'DurationField'))):
            return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)
        if (lhs_output and rhs_output and self.connector == self.SUB and
            lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and
                lhs_output.get_internal_type() == rhs_output.get_internal_type()):
            return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection)
        expressions = []
        expression_params = []
        sql, params = compiler.compile(self.lhs)
        expressions.append(sql)
        expression_params.extend(params)
        sql, params = compiler.compile(self.rhs)
        expressions.append(sql)
        expression_params.extend(params)
        # order of precedence
        expression_wrapper = '(%s)'
        sql = connection.ops.combine_expression(self.connector, expressions)
        return expression_wrapper % sql, expression_params 
Example #19
Source File: expressions.py    From bioforum with MIT License 5 votes vote down vote up
def _combine(self, other, connector, reversed):
        if not hasattr(other, 'resolve_expression'):
            # everything must be resolvable to an expression
            if isinstance(other, datetime.timedelta):
                other = DurationValue(other, output_field=fields.DurationField())
            else:
                other = Value(other)

        if reversed:
            return CombinedExpression(other, connector, self)
        return CombinedExpression(self, connector, other)

    #############
    # OPERATORS #
    ############# 
Example #20
Source File: expressions.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def compile(self, side, compiler, connection):
        if not isinstance(side, DurationValue):
            try:
                output = side.output_field
            except FieldError:
                pass
            else:
                if output.get_internal_type() == 'DurationField':
                    sql, params = compiler.compile(side)
                    return connection.ops.format_for_duration_arithmetic(sql), params
        return compiler.compile(side) 
Example #21
Source File: views.py    From pythonic-news with GNU Affero General Public License v3.0 4 votes vote down vote up
def _front_page(paging_size=settings.PAGING_SIZE, page=0, add_filter={}, add_q=[], as_of=None, days_back=50):
    # TODO: weighting https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
    # (P-1) / (T+2)^G
    if as_of is None:
        now = timezone.now()
    else:
        now = as_of
    if connection.vendor == 'postgresql':
        now_value = Value(now, output_field=fields.DateTimeField())
        submission_age_float = ExpressionWrapper(  ( now_value - F('created_at')), output_field=fields.DurationField())
        submission_age_hours = ExpressionWrapper(Extract(F('tf'), 'epoch') / 60 / 60 + 2.1 , output_field=fields.FloatField())
        real_p = ExpressionWrapper(F('points') - 1, output_field=fields.FloatField())
        formula = ExpressionWrapper(   F('p') / ( Power(F('tfh'), F('g'))  +0.001)   , output_field=fields.FloatField())
        return Story.objects.select_related('user')\
                .filter(duplicate_of__isnull=True)\
                .filter(points__gte=1) \
                .filter(created_at__gte=now - datetime.timedelta(days=days_back)) \
                .filter(created_at__lte=now) \
                .filter(**add_filter) \
                .annotate(tf=submission_age_float) \
                .annotate(tfh=submission_age_hours) \
                .annotate(p=real_p) \
                .annotate(g=Value(1.8, output_field=fields.FloatField())) \
                .annotate(formula=formula) \
                .order_by('-formula')[(page*paging_size):(page+1)*(paging_size)]
    elif connection.vendor == 'sqlite':
        now_value = Value(now, output_field=fields.DateTimeField())
        submission_age_float = ExpressionWrapper(  ( now_value - F('created_at')), output_field=fields.FloatField())
        submission_age_hours = ExpressionWrapper(F('tf') / 60 / 60 / 1000000 + 2.1 , output_field=fields.FloatField())
        real_p = ExpressionWrapper(F('points') - 1, output_field=fields.FloatField())
        formula = ExpressionWrapper(   F('p') / ( Power(F('tfh'), F('g'))  +0.001)   , output_field=fields.FloatField())
        return Story.objects.select_related('user')\
                .filter(duplicate_of__isnull=True)\
                .filter(points__gte=1) \
                .filter(created_at__gte=now - datetime.timedelta(days=days_back)) \
                .filter(created_at__lte=now) \
                .filter(**add_filter) \
                .annotate(tf=submission_age_float) \
                .annotate(tfh=submission_age_hours) \
                .annotate(p=real_p) \
                .annotate(g=Value(1.8, output_field=fields.FloatField())) \
                .annotate(formula=formula) \
                .order_by('-formula')[(page*paging_size):(page+1)*(paging_size)]
    else: 
        raise NotImplementedError("No frontpage magic for database engine %s implemented"%(connection.vendor)) 
Example #22
Source File: overview.py    From helfertool with GNU Affero General Public License v3.0 4 votes vote down vote up
def overview(request, event_url_name):
    event = get_object_or_404(Event, url_name=event_url_name)

    # permission
    if not event.is_admin(request.user):
        return nopermission(request)

    num_helpers = event.helper_set.count()

    num_coordinators = event.all_coordinators.count()

    num_vegetarians = event.helper_set.filter(vegetarian=True).count()

    num_shift_slots = Shift.objects.filter(job__event=event).aggregate(
        Sum('number'))['number__sum']

    empty_slots_expr = ExpressionWrapper(F('number') - F('num_helpers'),
                                         output_field=fields.IntegerField())
    num_empty_shift_slots = Shift.objects.filter(job__event=event) \
        .annotate(num_helpers=Count('helper')) \
        .annotate(empty_slots=empty_slots_expr) \
        .aggregate(Sum('empty_slots'))['empty_slots__sum']

    total_duration = ExpressionWrapper((F('end') - F('begin')) * F('number'),
                                       output_field=fields.DurationField())
    try:
        hours_total = Shift.objects.filter(job__event=event) \
                           .annotate(duration=total_duration) \
                           .aggregate(Sum('duration'))['duration__sum']
    except (OperationalError, OverflowError):
        hours_total = None
    except Exception as e:
        # handle psycopg2.DataError without importing psycopg2
        # happens on overflow with postgresql
        if 'DataError' in str(e.__class__):
            hours_total = None
        else:
            raise e

    # render
    context = {'event': event,
               'num_helpers': num_helpers,
               'num_coordinators': num_coordinators,
               'num_vegetarians': num_vegetarians,
               'num_shift_slots': num_shift_slots,
               'num_empty_shift_slots': num_empty_shift_slots,
               'hours_total': hours_total}
    return render(request, 'statistic/overview.html', context)