我们从Python开源项目中,提取了以下8个代码示例,用于说明如何使用django.db.models.Func()。
def _rewrite_expression(self, expr): ''' Rewrite rhs of expressions. ''' if isinstance(expr, models.expressions.F): field, _ = self._get_field(expr.name) if not isinstance(field, TranslatedVirtualField): return expr return field.as_sql(fallback=field.language is None, bare_lookup=expr.name) elif isinstance(expr, models.expressions.CombinedExpression): return models.expressions.CombinedExpression( self._rewrite_expression(expr.lhs), expr.connector, self._rewrite_expression(expr.rhs) ) elif isinstance(expr, models.Count): return models.Count( self._rewrite_expression(expr.source_expressions[0]) ) elif isinstance(expr, models.Func): new_expressions = [] for expression in expr.source_expressions: new_expressions.append(self._rewrite_expression(expression)) kwargs = {} if hasattr(expr, 'output_field'): kwargs['output_field'] = expr.output_field if hasattr(expr, 'desc') and expr.desc is True: kwargs['desc'] = True return type(expr)(*new_expressions, **kwargs) else: return expr
def send_reminder_messages(today=None): if today is None: today = timezone.now().date() votes = (Vote.objects .filter(published_at__isnull=False, valid_until__isnull=False) .exclude(submission_form__submission__workflow_lane=SUBMISSION_LANE_LOCALEC) .exclude(submission_form__submission__is_finished=True) .annotate(valid_until_date=Func(F('valid_until'), function='DATE'))) for vote in votes.filter( valid_until_date=Func(today + timedelta(days=21), function='DATE')): assert vote.result == '1' send_vote_reminder_submitter(vote) for vote in votes.filter( valid_until_date=Func(today + timedelta(days=7), function='DATE')): assert vote.result == '1' send_vote_reminder_office(vote) for vote in votes.filter( valid_until_date=Func(today - timedelta(days=1), function='DATE')): assert vote.result == '1' send_vote_expired(vote) tmp_votes = (Vote.objects .exclude(result__in=PERMANENT_VOTE_RESULTS) .exclude(_currently_published_for=None) .annotate(published_date=Func(F('published_at'), function='DATE'))) for vote in tmp_votes.filter( published_date=Func(today - timedelta(days=183), function='DATE')): send_temporary_vote_reminder_submitter(vote) for vote in tmp_votes.filter( published_date=Func(today - timedelta(days=365), function='DATE')): send_temporary_vote_reminder(vote)
def as_oracle(self, compiler, connection): # we can't mix TextField (NCLOB) and CharField (NVARCHAR), so convert # all fields to NCLOB when we expect NCLOB if self.output_field.get_internal_type() == 'TextField': class ToNCLOB(Func): function = 'TO_NCLOB' expressions = [ ToNCLOB(expression) for expression in self.get_source_expressions()] clone = self.copy() clone.set_source_expressions(expressions) return super(Coalesce, clone).as_sql(compiler, connection) return self.as_sql(compiler, connection)
def all_sorted(cls): return cls.objects.filter(display=True).order_by(Func(F('unit_name'), function='LOWER'))
def returns(request, acct_ignore=None): """ BASIC RETURNS MODULE: Returns a list of all the historic returns associated with a user's investment options. OUTPUT: A JSON containing a list of all the historic returns associated with that investment option, keys are the symbol of that option. {'returns': <list of len 3>, 'benchmark': <list of len 3>, 'benchmarkName': <string> } """ if not acct_ignore: acct_ignore = [] profile = request.user.profile quovo_user = profile.quovo_user user_returns_dict = {'yearToDate': 0.0, 'twoYearReturns': 0.0, 'oneYearReturns': 0.0} try: user_returns_dict = quovo_user.get_user_returns(acct_ignore=acct_ignore) except: pass display_returns = [ user_returns_dict['year_to_date'], user_returns_dict['one_year_return'], user_returns_dict['two_year_return'] ] display_returns_normalized = [round(display_return, 2) for display_return in display_returns] age = profile.get_age() bench = Benchmark.objects.annotate(abs_diff=Func(F('age_group') - age, function='ABS')).order_by('abs_diff').first() bench_mark_returns = bench.get_returns_wrapped() bench_mark_returns = [ bench_mark_returns["year_to_date"], bench_mark_returns["one_year_return"], bench_mark_returns["two_year_return"] ] bench_mark_returns_normalized = [round(bench_mark_return, 2) for bench_mark_return in bench_mark_returns] return Vestivise.network_response({ "returns": display_returns_normalized, "benchmark": bench_mark_returns_normalized, "benchmarkName": bench.name })
def risk_age_profile(request, acct_ignore=None): profile = request.user.profile age = profile.get_age() quovo_user = profile.quovo_user user_bond_equity = None if acct_ignore: user_bond_equity = quovo_user.get_user_bond_equity(acct_ignore=acct_ignore) else: latest_bond_equity = quovo_user.user_bond_equity.latest('created_at') user_bond_equity = latest_bond_equity if quovo_user.user_bond_equity.exists() else None stock_total = 0 if not user_bond_equity else user_bond_equity.equity bond_total = 0 if not user_bond_equity else user_bond_equity.bond bench = Benchmark.objects.annotate(abs_diff=Func(F('age_group') - age, function='ABS')).order_by('abs_diff').first() bench_bond_stock = bench.get_stock_bond_split() bench_stock_percent = bench_bond_stock.get("stock") bench_bond_percent = bench_bond_stock.get("bond") average_stock = 0 average_bond = 0 if AverageUserBondEquity.objects.exists(): average_user_bond_equity = AverageUserBondEquity.objects.latest('created_at') average_stock = average_user_bond_equity.equity average_bond = average_user_bond_equity.bond age_group = age_map(profile.get_age()) if age_group < 20: age_group = 20 elif age_group > 80: age_group = 80 return Vestivise.network_response({ "stock": int(round(stock_total)), "bond": int(round(bond_total)), "benchStock": bench_stock_percent * 100, "benchBond": bench_bond_percent * 100, "avgStock": int(round(average_stock)), "avgBond": int(round(average_bond)), "ageRange": "{}-{}".format(str(age_group-4), str(age_group)) })