本文整理汇总了Python中django.db.models.functions.Cast方法的典型用法代码示例。如果您正苦于以下问题:Python functions.Cast方法的具体用法?Python functions.Cast怎么用?Python functions.Cast使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models.functions
的用法示例。
在下文中一共展示了functions.Cast方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_average_execution_time_grouped
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def get_average_execution_time_grouped(self, from_date: datetime.datetime,
to_date: datetime.datetime) -> Optional[datetime.timedelta]:
return self.select_related(
'ethereum_tx', 'ethereum_tx__block'
).exclude(
ethereum_tx__block=None,
).annotate(
interval=Cast(F('ethereum_tx__block__timestamp') - F('created'),
output_field=DurationField())
).filter(
created__range=(from_date, to_date)
).annotate(
created_date=TruncDate('created')
).values(
'created_date'
).annotate(
average_execution_time=Avg('interval')
).values('created_date', 'average_execution_time').order_by('created_date')
示例2: check_if_inventory_linked
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def check_if_inventory_linked(instance: Inventory, action: Text, **kwargs) -> NoReturn:
if 'loaddata' in sys.argv or kwargs.get('raw', False): # nocv
return
if action != "pre_remove":
return
removing_inventories = instance.inventories.filter(pk__in=kwargs['pk_set'])
check_id = removing_inventories.values_list('id', flat=True)
linked_templates = Template.objects.filter(inventory__iregex=r'^[0-9]{1,128}$').\
annotate(inventory__id=Cast('inventory', IntegerField())).\
filter(inventory__id__in=check_id)
linked_periodic_tasks = PeriodicTask.objects.filter(_inventory__in=check_id)
if linked_periodic_tasks.exists() or linked_templates.exists():
raise_linked_error(
linked_templates=list(linked_templates.values_list('id', flat=True)),
linked_periodic_tasks=list(
linked_periodic_tasks.values_list('id', flat=True)
),
)
示例3: get_item_report
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def get_item_report(qs, total_log_count, **kwargs):
if qs.count() == 0:
return None
min_count = kwargs.get('min_count', max(1, int(MINIMUM_THRESHOLD * total_log_count)))
results = list(
qs.values(
'item',
name=F('item__name'),
icon=F('item__icon'),
).annotate(
count=Count('pk'),
min=Min('quantity'),
max=Max('quantity'),
avg=Avg('quantity'),
drop_chance=Cast(Count('pk'), FloatField()) / total_log_count * 100,
qty_per_100=Cast(Sum('quantity'), FloatField()) / total_log_count * 100,
).filter(count__gt=min_count).order_by('-count')
)
return results
示例4: get_feedback
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
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')
)
示例5: get_available_approvals
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def get_available_approvals(self, as_user):
those_with_max_priority = With(
TransitionApproval.objects.filter(
workflow=self.workflow, status=PENDING
).values(
'workflow', 'object_id', 'transition'
).annotate(min_priority=Min('priority'))
)
workflow_objects = With(
self.wokflow_object_class.objects.all(),
name="workflow_object"
)
approvals_with_max_priority = those_with_max_priority.join(
self._authorized_approvals(as_user),
workflow_id=those_with_max_priority.col.workflow_id,
object_id=those_with_max_priority.col.object_id,
transition_id=those_with_max_priority.col.transition_id,
).with_cte(
those_with_max_priority
).annotate(
object_id_as_str=Cast('object_id', CharField(max_length=200)),
min_priority=those_with_max_priority.col.min_priority
).filter(min_priority=F("priority"))
return workflow_objects.join(
approvals_with_max_priority, object_id_as_str=Cast(workflow_objects.col.pk, CharField(max_length=200))
).with_cte(
workflow_objects
).filter(transition__source_state=getattr(workflow_objects.col, self.field_name + "_id"))
示例6: index
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def index(request, event=None):
event = viewutil.get_event(event)
eventParams = {}
if event.id:
eventParams['event'] = event.id
agg = Donation.objects.filter(
transactionstate='COMPLETED', testdonation=False, **eventParams
).aggregate(
amount=Cast(Coalesce(Sum('amount'), 0), output_field=FloatField()),
count=Count('amount'),
max=Cast(Coalesce(Max('amount'), 0), output_field=FloatField()),
avg=Cast(Coalesce(Avg('amount'), 0), output_field=FloatField()),
)
agg['target'] = float(event.targetamount)
count = {
'runs': filters.run_model_query('run', eventParams).count(),
'prizes': filters.run_model_query('prize', eventParams).count(),
'bids': filters.run_model_query('bid', eventParams).count(),
'donors': filters.run_model_query('donorcache', eventParams)
.values('donor')
.distinct()
.count(),
}
if 'json' in request.GET:
return HttpResponse(
json.dumps({'count': count, 'agg': agg}, ensure_ascii=False,),
content_type='application/json;charset=utf-8',
)
return views_common.tracker_response(
request, 'tracker/index.html', {'agg': agg, 'count': count, 'event': event}
)
示例7: _populate_aws_daily_table
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def _populate_aws_daily_table(self):
included_fields = [
"cost_entry_bill_id",
"cost_entry_product_id",
"cost_entry_pricing_id",
"cost_entry_reservation_id",
"line_item_type",
"usage_account_id",
"usage_type",
"operation",
"availability_zone",
"resource_id",
"tax_type",
"product_code",
"tags",
]
annotations = {
"usage_start": Cast("usage_start", DateTimeField()),
"usage_end": Cast("usage_start", DateTimeField()),
"usage_amount": Sum("usage_amount"),
"normalization_factor": Max("normalization_factor"),
"normalized_usage_amount": Sum("normalized_usage_amount"),
"currency_code": Max("currency_code"),
"unblended_rate": Max("unblended_rate"),
"unblended_cost": Sum("unblended_cost"),
"blended_rate": Max("blended_rate"),
"blended_cost": Sum("blended_cost"),
"public_on_demand_cost": Sum("public_on_demand_cost"),
"public_on_demand_rate": Max("public_on_demand_rate"),
}
entries = AWSCostEntryLineItem.objects.values(*included_fields).annotate(**annotations)
for entry in entries:
daily = AWSCostEntryLineItemDaily(**entry)
daily.save()
示例8: _populate_daily_table
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def _populate_daily_table(self):
included_fields = [
"cost_entry_bill_id",
"cost_entry_product_id",
"cost_entry_pricing_id",
"cost_entry_reservation_id",
"line_item_type",
"usage_account_id",
"usage_type",
"operation",
"availability_zone",
"resource_id",
"tax_type",
"product_code",
"tags",
]
annotations = {
"usage_start": Cast("usage_start", DateTimeField()),
"usage_end": Cast("usage_start", DateTimeField()),
"usage_amount": Sum("usage_amount"),
"normalization_factor": Max("normalization_factor"),
"normalized_usage_amount": Sum("normalized_usage_amount"),
"currency_code": Max("currency_code"),
"unblended_rate": Max("unblended_rate"),
"unblended_cost": Sum("unblended_cost"),
"blended_rate": Max("blended_rate"),
"blended_cost": Sum("blended_cost"),
"public_on_demand_cost": Sum("public_on_demand_cost"),
"public_on_demand_rate": Max("public_on_demand_rate"),
}
entries = AWSCostEntryLineItem.objects.values(*included_fields).annotate(**annotations)
for entry in entries:
daily = AWSCostEntryLineItemDaily(**entry)
daily.save()
示例9: get_tokens_usage
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def get_tokens_usage(self) -> Optional[List[Dict[str, Any]]]:
"""
:return: List of Dict 'gas_token', 'total', 'number', 'percentage'
"""
total = self.deployed_and_checked().annotate(_x=Value(1)).values('_x').annotate(total=Count('_x')
).values('total')
return self.deployed_and_checked().values('payment_token').annotate(
total=Subquery(total, output_field=models.IntegerField())
).annotate(
number=Count('safe_id'), percentage=Cast(100.0 * Count('pk') / F('total'),
models.FloatField()))
示例10: get_average_execution_time
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def get_average_execution_time(self, from_date: datetime.datetime,
to_date: datetime.datetime) -> Optional[datetime.timedelta]:
return self.select_related(
'ethereum_tx', 'ethereum_tx__block'
).exclude(
ethereum_tx__block=None,
).annotate(
interval=Cast(F('ethereum_tx__block__timestamp') - F('created'),
output_field=DurationField())
).filter(
created__range=(from_date, to_date)
).aggregate(median=Avg('interval'))['median']
示例11: create_activity_upcoming_notifications
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def create_activity_upcoming_notifications():
# Oh oh, this is a bit complex. As notification.context is a JSONField, the participants_already_notified subquery
# would return a jsonb object by default (which can't be compared to integer).
# We can work around this by transforming the property value to text ("->>" lookup) and then casting to integer
with timer() as t:
participants_already_notified = Notification.objects.\
order_by().\
filter(type=NotificationType.ACTIVITY_UPCOMING.value).\
exclude(context__activity_participant=None).\
values_list(Cast(KeyTextTransform('activity_participant', 'context'), IntegerField()), flat=True)
activities_due_soon = Activity.objects.order_by().due_soon()
participants = ActivityParticipant.objects.\
filter(activity__in=activities_due_soon).\
exclude(id__in=participants_already_notified).\
distinct()
for participant in participants:
Notification.objects.create(
type=NotificationType.ACTIVITY_UPCOMING.value,
user=participant.user,
expires_at=participant.activity.date.start,
context={
'group': participant.activity.place.group.id,
'place': participant.activity.place.id,
'activity': participant.activity.id,
'activity_participant': participant.id,
},
)
stats_utils.periodic_task('notifications__create_activity_upcoming_notifications', seconds=t.elapsed_seconds)
示例12: resources
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def resources(request):
resources = Resource.objects
resources = resources.select_related('module')
resources = resources.annotate(has_rating_i=Cast('has_rating_history', IntegerField()))
resources = resources.annotate(has_rating_f=Cast('has_rating_i', FloatField()))
resources = resources.annotate(priority=Ln(F('n_contests') + 1) + Ln(F('n_accounts') + 1) + 2 * F('has_rating_f'))
resources = resources.order_by('-priority')
return render(request, 'resources.html', {'resources': resources})
示例13: run
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def run(*args):
accounts = Account.objects
qs = accounts.filter(info__rating__isnull=False)
qs = qs.annotate(info_rating=Cast(JSONF('info__rating'), IntegerField()))
qs = qs.exclude(rating=F('info_rating'))
ret = qs.update(rating=F('info_rating'))
print(ret)
qs = accounts.filter(rating__isnull=False)
qs = qs.annotate(r50=F('rating') / 50)
qs = qs.exclude(rating50=F('r50'))
ret = qs.update(rating50=F('r50'))
print(ret)
示例14: create_spatial_unit
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def create_spatial_unit(self, data, project,
party=None, duplicate=None):
location_resources = []
location_objects = []
try:
location_group = self._format_repeat(data, ['location'])
for group in location_group:
geom = self._format_geometry(group)
attrs = dict(
project=project,
type=group['location_type'],
attributes=self._get_attributes(group, 'location')
)
if duplicate:
geom_type = GEOSGeometry(geom).geom_type
GeometryField = getattr(geo_models, geom_type + 'Field')
location = duplicate.spatial_units.annotate(
geom=Cast('geometry', GeometryField())
).get(geom=geom, **attrs)
else:
location = SpatialUnit.objects.create(geometry=geom,
**attrs)
location_resources.append(
self._get_resource_names(group, location, 'location')
)
location_objects.append(location)
except Exception as e:
raise InvalidXMLSubmission(_(
'Location error: {}'.format(e)))
return location_objects, location_resources
示例15: get_true_annotations_queryset
# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Cast [as 别名]
def get_true_annotations_queryset(self):
"""
Get FieldAnnotation queryset
"""
true_ann_qs = self.get_initial_queryset(FieldAnnotation)
# WARN: fields order makes sense here for list view
true_ann_only_fields = [
'status_id',
'modified_by_id',
'modified_date']
# TODO: move common annotations into get_initial_queryset()
# WARN: fields order makes sense here for list view
true_ann_qs_annotate = OrderedDict(
document_id=Cast('document_id', output_field=CharField()),
project_id=F('document__project_id'),
project_name=F('document__project__name'),
document_name=F('document__name'),
document_status=F('document__status__name'),
field_name=F('field__title'),
status_name=F('status__name'),
assignee_name=Case(When(Q(assignee__name__isnull=False) & ~Q(assignee__name=''), then=F('assignee__name')),
When(Q(assignee__first_name__isnull=False) & ~Q(assignee__first_name='') &
Q(assignee__last_name__isnull=False) & ~Q(assignee__last_name=''),
then=Concat(F('assignee__first_name'), Value(' '), F('assignee__last_name'))),
default=F('assignee__username'),
output_field=CharField()
)
)
# WARN: MUST HAVE the same
# 1. fields number
# 2. fields order
# for FieldAnnotation and FieldAnnotationFalseMatch querysets to perform UNION !!!
# so .values() and .annotate() applies THE SAME fields number and order
true_ann_fields = self.common_fields + true_ann_only_fields
true_ann_qs = true_ann_qs.values(*true_ann_fields).annotate(**true_ann_qs_annotate)
return true_ann_qs