本文整理匯總了Python中django.db.models.Value方法的典型用法代碼示例。如果您正苦於以下問題:Python models.Value方法的具體用法?Python models.Value怎麽用?Python models.Value使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.db.models
的用法示例。
在下文中一共展示了models.Value方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_queryset
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def get_queryset(self):
date = self._extract_date()
user = self.request.user
queryset = get_user_model().objects.values("id")
queryset = queryset.annotate(date=Value(date, DateField()))
# last_reported_date filter is set, a date can only be calucated
# for users with either at least one absence or report
if date is None:
users_with_reports = Report.objects.values("user").distinct()
users_with_absences = Absence.objects.values("user").distinct()
active_users = users_with_reports.union(users_with_absences)
queryset = queryset.filter(id__in=active_users)
queryset = queryset.annotate(
pk=Concat("id", Value("_"), "date", output_field=CharField())
)
if not user.is_superuser:
queryset = queryset.filter(Q(id=user.id) | Q(supervisors=user))
return queryset
示例2: for_user
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def for_user(self, user, start, end):
"""Get employments in given time frame for current user.
This includes overlapping employments.
:param User user: The user of the searched employments
:param datetime.date start: start of time frame
:param datetime.date end: end of time frame
:returns: queryset of employments
"""
# end date NULL on database is like employment is ending today
queryset = self.annotate(
end=functions.Coalesce("end_date", models.Value(date.today()))
)
return queryset.filter(user=user).exclude(
models.Q(end__lt=start) | models.Q(start_date__gt=end)
)
示例3: redirect_staff
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def redirect_staff(self):
target_work_staff = set()
kept_staff_ids = []
# Only one query: put self.target_work's Staff objects first in the list
queryset = (Staff.objects.filter(work__in=self.works_to_merge)
.annotate(belongs_to_target_work=Case(
When(work_id=self.target_work.id, then=Value(1)),
default=Value(0), output_field=IntegerField()))
.order_by('-belongs_to_target_work')
.values_list('id', 'work_id', 'artist_id', 'role_id'))
for staff_id, work_id, artist_id, role_id in queryset:
if work_id == self.target_work.id: # This condition will be met for the first iterations
target_work_staff.add((artist_id, role_id))
# Now we are sure we know every staff of the final work
elif (artist_id, role_id) not in target_work_staff:
kept_staff_ids.append(staff_id)
Staff.objects.filter(work__in=self.works_to_merge).exclude(work_id=self.target_work.id).exclude(
id__in=kept_staff_ids).delete()
Staff.objects.filter(id__in=kept_staff_ids).update(work_id=self.target_work.id)
示例4: get_queue_size_params
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def get_queue_size_params(queue, queue_size, num_in_queue, batch_size, irr_queue):
'''
Get the sql parameters for the number of items to add to the queue
'''
# if there is less space in the queue than the default number of
# elements to add, or we are trying to fill the queue to the top
# (irr_queue=None in the second case)
if (queue_size - num_in_queue < batch_size) or not(irr_queue):
sample_size_sql, sample_size_params = (Queue.objects.filter(pk=queue.pk)
.annotate(sample_size=F('length') - Count('data'))
.values('sample_size')
.query.sql_with_params())
else:
# just add the number requested (some percent of the batch size)
sample_size_sql, sample_size_params = (Queue.objects.filter(pk=queue.pk)
.annotate(sample_size=Value(batch_size, IntegerField()))
.values('sample_size')
.query.sql_with_params())
return sample_size_sql, sample_size_params
示例5: as_vector
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def as_vector(self, texts, for_autocomplete=False):
"""
Converts an array of strings into a SearchVector that can be indexed.
"""
texts = [(text.strip(), weight) for text, weight in texts]
texts = [(text, weight) for text, weight in texts if text]
if not texts:
return EMPTY_VECTOR
search_config = self.autocomplete_config if for_autocomplete else self.config
return ADD([
SearchVector(Value(text, output_field=TextField()), weight=weight, config=search_config)
for text, weight in texts
])
示例6: __init__
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def __init__(self, expression, pos, length=None, **extra):
"""
expression: the name of a field, or an expression returning a string
pos: an integer > 0, or an expression returning an integer
length: an optional number of characters to return
"""
if not hasattr(pos, 'resolve_expression'):
if pos < 1:
raise ValueError("'pos' must be greater than 0")
pos = Value(pos)
expressions = [expression, pos]
if length is not None:
if not hasattr(length, 'resolve_expression'):
length = Value(length)
expressions.append(length)
super(Substr, self).__init__(*expressions, **extra)
示例7: credit_notes
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def credit_notes(request, form):
''' Shows all of the credit notes in the system. '''
notes = commerce.CreditNote.objects.all().select_related(
"creditnoterefund",
"creditnoteapplication",
"invoice",
"invoice__user__attendee__attendeeprofilebase",
)
return QuerysetReport(
"Credit Notes",
["id",
"invoice__user__attendee__attendeeprofilebase__invoice_recipient",
"status", "value"],
notes,
headings=["id", "Owner", "Status", "Value"],
link_view=views.credit_note,
)
示例8: pre_filter
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def pre_filter(self, queryset, user):
''' Returns all of the items from queryset where the date falls into
any specified range, but not yet where the stock limit is not yet
reached.'''
now = timezone.now()
# Keep items with no start time, or start time not yet met.
queryset = queryset.filter(Q(start_time=None) | Q(start_time__lte=now))
queryset = queryset.filter(Q(end_time=None) | Q(end_time__gte=now))
# Filter out items that have been reserved beyond the limits
quantity_or_zero = self._calculate_quantities(user)
remainder = Case(
When(limit=None, then=Value(_BIG_QUANTITY)),
default=F("limit") - Sum(quantity_or_zero),
)
queryset = queryset.annotate(remainder=remainder)
queryset = queryset.filter(remainder__gt=0)
return queryset
示例9: __init__
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def __init__(self, *expressions, **kwargs):
separator = kwargs.pop("separator", ",")
if len(kwargs) > 0:
raise ValueError(
"Invalid keyword arguments for ConcatWS: {}".format(
",".join(kwargs.keys())
)
)
if len(expressions) < 2:
raise ValueError("ConcatWS must take at least two expressions")
if not hasattr(separator, "resolve_expression"):
separator = Value(separator)
# N.B. if separator is "," we could potentially use list field
output_field = TextField()
super().__init__(separator, *expressions, output_field=output_field)
示例10: list_with_post
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def list_with_post(self, request):
"""Endpoint handler."""
if self.is_search_request():
search = self.search()
page = self.paginate_queryset(search)
if page is None:
items = search
else:
items = page
try:
primary_keys = []
order_map_cases = []
for order, item in enumerate(items):
pk = item[self.primary_key_field]
primary_keys.append(pk)
order_map_cases.append(When(pk=pk, then=Value(order)))
queryset = (
self.get_queryset()
.filter(pk__in=primary_keys)
.order_by(Case(*order_map_cases, output_field=IntegerField()).asc())
)
except KeyError:
raise KeyError(
"Combined viewset requires that your index contains a field with "
"the primary key. By default this field is called 'id', but you "
"can change it by setting primary_key_field."
)
# Pagination must be handled differently.
serializer = self.get_serializer(queryset, many=True)
if page is not None:
return self.get_paginated_response(serializer.data)
return Response(serializer.data)
else:
queryset = self.filter_queryset(self.get_queryset())
return self.paginate_response(queryset)
示例11: annotations
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def annotations(self):
"""Create dictionary for query annotations.
Returns:
(Dict): query annotations dictionary
"""
units_fallback = self._mapper.report_type_map.get("cost_units_fallback")
annotations = {
"date": self.date_trunc("usage_start"),
"cost_units": Coalesce(self._mapper.cost_units_key, Value(units_fallback)),
}
if self._mapper.usage_units_key:
units_fallback = self._mapper.report_type_map.get("usage_units_fallback")
annotations["usage_units"] = Coalesce(self._mapper.usage_units_key, Value(units_fallback))
# { query_param: database_field_name }
fields = self._mapper.provider_map.get("annotations")
prefix_removed_parameters_list = list(
map(
lambda x: x if ":" not in x else x.split(":", maxsplit=1)[1],
self.parameters.get("group_by", {}).keys(),
)
)
for q_param, db_field in fields.items():
if q_param in prefix_removed_parameters_list:
annotations[q_param] = F(db_field)
return annotations
示例12: _build_sum
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def _build_sum(self, query, annotations):
"""Build the sum results for the query."""
sum_units = {}
query_sum = self.initialize_totals()
if not self.parameters.parameters.get("compute_count"):
query_sum.pop("count", None)
cost_units_fallback = self._mapper.report_type_map.get("cost_units_fallback")
usage_units_fallback = self._mapper.report_type_map.get("usage_units_fallback")
count_units_fallback = self._mapper.report_type_map.get("count_units_fallback")
if query.exists():
sum_annotations = {"cost_units": Coalesce(self._mapper.cost_units_key, Value(cost_units_fallback))}
if self._mapper.usage_units_key:
units_fallback = self._mapper.report_type_map.get("usage_units_fallback")
sum_annotations["usage_units"] = Coalesce(self._mapper.usage_units_key, Value(units_fallback))
sum_query = query.annotate(**sum_annotations)
units_value = sum_query.values("cost_units").first().get("cost_units", cost_units_fallback)
sum_units = {"cost_units": units_value}
if self._mapper.usage_units_key:
units_value = sum_query.values("usage_units").first().get("usage_units", usage_units_fallback)
sum_units["usage_units"] = units_value
if annotations.get("count_units"):
sum_units["count_units"] = count_units_fallback
query_sum = self.calculate_total(**sum_units)
else:
sum_units["cost_units"] = cost_units_fallback
if annotations.get("count_units"):
sum_units["count_units"] = count_units_fallback
if annotations.get("usage_units"):
sum_units["usage_units"] = usage_units_fallback
query_sum.update(sum_units)
self._pack_data_object(query_sum, **self._mapper.PACK_DEFINITIONS)
return query_sum
示例13: annotations
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def annotations(self):
"""Create dictionary for query annotations.
Returns:
(Dict): query annotations dictionary
"""
units_fallback = self._mapper.report_type_map.get("cost_units_fallback")
annotations = {
"date": self.date_trunc("usage_start"),
"cost_units": Coalesce(self._mapper.cost_units_key, Value(units_fallback)),
}
if self._mapper.usage_units_key:
units_fallback = self._mapper.report_type_map.get("usage_units_fallback")
annotations["usage_units"] = Coalesce(self._mapper.usage_units_key, Value(units_fallback))
# { query_param: database_field_name }
fields = self._mapper.provider_map.get("annotations")
for q_param, db_field in fields.items():
annotations[q_param] = Concat(db_field, Value(""))
return annotations
示例14: _build_sum
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def _build_sum(self, query):
"""Build the sum results for the query."""
sum_units = {}
query_sum = self.initialize_totals()
cost_units_fallback = self._mapper.report_type_map.get("cost_units_fallback")
# usage_units_fallback = self._mapper.report_type_map.get('usage_units_fallback')
count_units_fallback = self._mapper.report_type_map.get("count_units_fallback")
if query.exists():
sum_annotations = {"cost_units": Coalesce(self._mapper.cost_units_key, Value(cost_units_fallback))}
# if self._mapper.usage_units_key:
# units_fallback = self._mapper.report_type_map.get('usage_units_fallback')
# sum_annotations['usage_units'] = Coalesce(self._mapper.usage_units_key,
# Value(units_fallback))
sum_query = query.annotate(**sum_annotations)
units_value = sum_query.values("cost_units").first().get("cost_units", cost_units_fallback)
sum_units = {"cost_units": units_value}
# if self._mapper.usage_units_key:
# units_value = sum_query.values('usage_units').first().get('usage_units',
# usage_units_fallback)
# sum_units['usage_units'] = units_value
if self._mapper.report_type_map.get("annotations", {}).get("count_units"):
sum_units["count_units"] = count_units_fallback
query_sum = self.calculate_total(**sum_units)
else:
sum_units["cost_units"] = cost_units_fallback
if self._mapper.report_type_map.get("annotations", {}).get("count_units"):
sum_units["count_units"] = count_units_fallback
# if self._mapper.report_type_map.get('annotations', {}).get('usage_units'):
# sum_units['usage_units'] = usage_units_fallback
query_sum.update(sum_units)
self._pack_data_object(query_sum, **self._mapper.PACK_DEFINITIONS)
return query_sum
示例15: _populate_daily_summary_table
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Value [as 別名]
def _populate_daily_summary_table(self):
included_fields = ["usage_start", "usage_end", "usage_account_id", "availability_zone", "tags"]
annotations = {
"product_family": Concat("cost_entry_product__product_family", Value("")),
"product_code": Concat("cost_entry_product__service_code", Value("")),
"region": Concat("cost_entry_product__region", Value("")),
"instance_type": Concat("cost_entry_product__instance_type", Value("")),
"unit": Concat("cost_entry_pricing__unit", Value("")),
"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"),
"resource_count": Count("resource_id", distinct=True),
"resource_ids": ArrayAgg("resource_id", distinct=True),
}
entries = AWSCostEntryLineItemDaily.objects.values(*included_fields).annotate(**annotations)
for entry in entries:
alias = AWSAccountAlias.objects.filter(account_id=entry["usage_account_id"])
alias = list(alias).pop() if alias else None
summary = AWSCostEntryLineItemDailySummary(**entry, account_alias=alias)
summary.save()
self.current_month_total += entry["unblended_cost"] + entry["unblended_cost"] * Decimal(0.1)
AWSCostEntryLineItemDailySummary.objects.update(markup_cost=F("unblended_cost") * 0.1)