本文整理匯總了Python中django.db.models.F屬性的典型用法代碼示例。如果您正苦於以下問題:Python models.F屬性的具體用法?Python models.F怎麽用?Python models.F使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類django.db.models
的用法示例。
在下文中一共展示了models.F屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: notify_stock_limits
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def notify_stock_limits(self):
"""
Notifies the correct parties of inventory items stocking status
"""
subject = _(u"Products stocked below limit")
for l in Location.objects.filter(enabled=True):
out_of_stock = Inventory.objects.filter(
location=l,
amount_stocked__lt=F('amount_minimum')
)
table = CsvTable()
table.addheader(['PRODUCT', 'MINIMUM', 'STOCKED'])
for i in out_of_stock:
table.addrow([i.product.code, i.amount_minimum, i.amount_stocked])
if Configuration.notify_location():
recipient = l.manager.email if l.manager else l.email
send_table(self.mail_sender, recipient, subject, table)
if self.mail_recipient:
send_table(self.mail_sender, self.mail_recipient, subject, table)
示例2: handle_rollover
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def handle_rollover(inst: Instrument, new_bar: DailyBar):
"""
換月處理, 基差=新合約收盤價-舊合約收盤價, 從今日起之前的所有連續合約的OHLC加上基差
"""
product_code = re.findall('[A-Za-z]+', new_bar.code)[0]
old_bar = DailyBar.objects.filter(exchange=inst.exchange, code=inst.last_main, time=new_bar.time).first()
main_bar = MainBar.objects.get(
exchange=inst.exchange, product_code=product_code, time=new_bar.time)
if old_bar is None:
old_close = new_bar.close
else:
old_close = old_bar.close
basis = new_bar.close - old_close
main_bar.basis = basis
basis = float(basis)
main_bar.save(update_fields=['basis'])
MainBar.objects.filter(exchange=inst.exchange, product_code=product_code, time__lte=new_bar.time).update(
open=F('open') + basis, high=F('high') + basis,
low=F('low') + basis, close=F('close') + basis, settlement=F('settlement') + basis)
示例3: filter_queryset
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def filter_queryset(self, request, queryset, view):
ordering = self.get_ordering(request, queryset, view)
if ordering:
f_ordering = []
for o in ordering:
if not o:
continue
if o[0] == "-":
f_ordering.append(F(o[1:]).desc(nulls_last=True))
else:
f_ordering.append(F(o).asc(nulls_last=True))
return queryset.order_by(*f_ordering)
return queryset
示例4: annotations
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def annotations(self):
"""Create dictionary for query annotations.
Returns:
(Dict): query annotations dictionary
"""
annotations = {"date": self.date_trunc("usage_start")}
# { query_param: database_field_name }
fields = self._mapper.provider_map.get("annotations")
for q_param, db_field in fields.items():
annotations[q_param] = F(db_field)
if (
"project" in self.parameters.parameters.get("group_by", {})
or "and:project" in self.parameters.parameters.get("group_by", {})
or "or:project" in self.parameters.parameters.get("group_by", {})
):
annotations["project"] = F("namespace")
return annotations
示例5: get_rank_window_function
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def get_rank_window_function(self, group_by_value):
"""Generate a limit ranking window function."""
tag_column = self._mapper.tag_column
rank_orders = []
rank_field = group_by_value.pop()
default_ordering = self._mapper.report_type_map.get("default_ordering")
if self.order_field == "delta" and "__" in self._delta:
delta_field_one, delta_field_two = self._delta.split("__")
rank_orders.append(getattr(F(delta_field_one) / F(delta_field_two), self.order_direction)())
elif self.parameters.get("order_by", default_ordering):
rank_orders.append(getattr(F(self.order_field), self.order_direction)())
if tag_column in rank_field:
rank_orders.append(self.get_tag_order_by(rank_field))
else:
rank_orders.append(getattr(F(rank_field), self.order_direction)())
return Window(expression=RowNumber(), partition_by=F("date"), order_by=rank_orders)
示例6: test_execute_query_with_wildcard_tag_filter
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def test_execute_query_with_wildcard_tag_filter(self):
"""Test that data is filtered to include entries with tag key."""
url = "?filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=monthly" # noqa: E501
query_params = self.mocked_query_params(url, AWSTagView)
handler = AWSTagQueryHandler(query_params)
tag_keys = handler.get_tag_keys()
filter_key = tag_keys[0]
tag_keys = ["tag:" + tag for tag in tag_keys]
with tenant_context(self.tenant):
totals = AWSCostEntryLineItemDailySummary.objects.filter(
usage_start__gte=self.dh.this_month_start
).aggregate(**{"cost": Sum(F("unblended_cost") + F("markup_cost"))})
url = f"?filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=monthly&filter[tag:{filter_key}]=*" # noqa: E501
query_params = self.mocked_query_params(url, AWSCostView)
handler = AWSReportQueryHandler(query_params)
data = handler.execute_query()
data_totals = data.get("total", {})
result = data_totals.get("cost", {}).get("total", {}).get("value")
self.assertEqual(result, totals["cost"])
示例7: test_populate_markup_cost_no_billsids
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def test_populate_markup_cost_no_billsids(self):
"""Test that the daily summary table is populated."""
summary_table_name = AZURE_REPORT_TABLE_MAP["line_item_daily_summary"]
summary_table = getattr(self.accessor.report_schema, summary_table_name)
query = self.accessor._get_db_obj_query(summary_table_name)
with schema_context(self.schema):
expected_markup = query.aggregate(markup=Sum(F("pretax_cost") * decimal.Decimal(0.1)))
expected_markup = expected_markup.get("markup")
summary_entry = summary_table.objects.all().aggregate(Min("usage_start"), Max("usage_start"))
start_date = summary_entry["usage_start__min"]
end_date = summary_entry["usage_start__max"]
self.accessor.populate_markup_cost(0.1, start_date, end_date, None)
with schema_context(self.schema):
query = self.accessor._get_db_obj_query(summary_table_name).aggregate(Sum("markup_cost"))
actual_markup = query.get("markup_cost__sum")
self.assertAlmostEqual(actual_markup, expected_markup, 6)
示例8: test_populate_markup_cost_no_billsids
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def test_populate_markup_cost_no_billsids(self):
"""Test that the daily summary table is populated."""
summary_table_name = AWS_CUR_TABLE_MAP["line_item_daily_summary"]
summary_table = getattr(self.accessor.report_schema, summary_table_name)
query = self.accessor._get_db_obj_query(summary_table_name)
with schema_context(self.schema):
expected_markup = query.aggregate(markup=Sum(F("unblended_cost") * decimal.Decimal(0.1)))
expected_markup = expected_markup.get("markup")
summary_entry = summary_table.objects.all().aggregate(Min("usage_start"), Max("usage_start"))
start_date = summary_entry["usage_start__min"]
end_date = summary_entry["usage_start__max"]
self.accessor.populate_markup_cost(0.1, start_date, end_date, None)
with schema_context(self.schema):
query = self.accessor._get_db_obj_query(summary_table_name).aggregate(Sum("markup_cost"))
actual_markup = query.get("markup_cost__sum")
self.assertAlmostEqual(actual_markup, expected_markup, 6)
示例9: filter_queryset
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def filter_queryset(self, queryset):
if self.request.user.is_anonymous():
self.permission_denied(self.request)
is_project = self.kwargs.get('is_project', None)
pk = self.kwargs.get('pk', None)
if is_project == "1":
queryset = queryset.filter(project__id=pk)
return queryset.annotate(response_count=Count("schedule_forms__project_form_instances")).select_related('schedule_forms', 'schedule_forms__xf', 'schedule_forms__em')
else:
project_id = get_object_or_404(Site, pk=pk).project.id
queryset = queryset.filter(Q(site__id=pk, schedule_forms__from_project=False)
| Q(project__id=project_id))
return queryset.annotate(
site_response_count=Count("schedule_forms__site_form_instances", ),
response_count=Count(Case(
When(project__isnull=False, schedule_forms__project_form_instances__site__id=pk, then=F('schedule_forms__project_form_instances')),
output_field=IntegerField(),
), distinct=True)
).select_related('schedule_forms','schedule_forms__xf', 'schedule_forms__em')
示例10: increase_usage
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def increase_usage(self, bytes):
# increase usage for this user based on document size
storage_qs = UserStorage.objects.filter(pk=self.request.user.storage.pk)
storage_qs.update(bytes_used=F("bytes_used") + bytes)
示例11: delete
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def delete(self, *args, **kwargs):
bytes_to_free = self.size
super().delete(*args, **kwargs)
storage_qs = UserStorage.objects.filter(pk=self.author.storage.pk)
storage_qs.update(bytes_used=F("bytes_used") - bytes_to_free)
示例12: get_expected_results
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def get_expected_results(self, **filter):
"""returns a list of dicts of the filtered user data
"""
return list(
get_user_model().objects.filter(**filter).annotate(
fullname=F('profile__name'), country=F('profile__country')
).values(*self.expected_result_keys))
示例13: get_expected_results
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def get_expected_results(self, **filter):
'''returns a list of dicts of the filtered user data
'''
return list(
get_user_model().objects.filter(**filter).annotate(
fullname=F('profile__name')).values(*self.expected_result_keys))
# This test fails on 'assert 1'. More users are added after setup called
示例14: get_available_approvals
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [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"))
示例15: delete
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import F [as 別名]
def delete(self, *args, **kwargs):
fields_after = self.form.fields.filter(order__gte=self.order)
fields_after.update(order=models.F("order") - 1)
DocumentSetFieldEntry.objects.filter(field_id=self.id).delete()
super(DocumentSetFormField, self).delete(*args, **kwargs)