本文整理汇总了Python中django.db.models.Min方法的典型用法代码示例。如果您正苦于以下问题:Python models.Min方法的具体用法?Python models.Min怎么用?Python models.Min使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.Min方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _populate_storage_summary
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def _populate_storage_summary(self, cluster_id=None):
"""Generate storage summary data."""
report_table_name = OCP_REPORT_TABLE_MAP["report"]
report_table = getattr(self.accessor.report_schema, report_table_name)
if cluster_id is None:
cluster_id = self.cluster_id
for _ in range(25):
pod = "".join(random.choice(string.ascii_lowercase) for _ in range(10))
namespace = "".join(random.choice(string.ascii_lowercase) for _ in range(10))
self.creator.create_ocp_usage_line_item(self.reporting_period, self.report, pod=pod, namespace=namespace)
self.creator.create_ocp_storage_line_item(self.reporting_period, self.report, pod=pod, namespace=namespace)
self.creator.create_ocp_node_label_line_item(self.reporting_period, self.report)
with schema_context(self.schema):
report_entry = report_table.objects.all().aggregate(Min("interval_start"), Max("interval_start"))
start_date = report_entry["interval_start__min"]
end_date = report_entry["interval_start__max"]
start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0)
end_date = end_date.replace(hour=0, minute=0, second=0, microsecond=0)
self.accessor.populate_node_label_line_item_daily_table(start_date, end_date, cluster_id)
self.accessor.populate_line_item_daily_table(start_date, end_date, cluster_id)
self.accessor.populate_storage_line_item_daily_table(start_date, end_date, cluster_id)
self.accessor.populate_storage_line_item_daily_summary_table(start_date, end_date, cluster_id)
示例2: _populate_pod_summary
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def _populate_pod_summary(self):
"""Generate pod summary data."""
report_table_name = OCP_REPORT_TABLE_MAP["report"]
report_table = getattr(self.accessor.report_schema, report_table_name)
cluster_id = "testcluster"
for _ in range(25):
self.creator.create_ocp_usage_line_item(self.reporting_period, self.report)
self.creator.create_ocp_node_label_line_item(self.reporting_period, self.report)
with schema_context(self.schema):
report_entry = report_table.objects.all().aggregate(Min("interval_start"), Max("interval_start"))
start_date = report_entry["interval_start__min"]
end_date = report_entry["interval_start__max"]
start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0)
end_date = end_date.replace(hour=0, minute=0, second=0, microsecond=0)
self.accessor.populate_node_label_line_item_daily_table(start_date, end_date, cluster_id)
self.accessor.populate_line_item_daily_table(start_date, end_date, cluster_id)
self.accessor.populate_line_item_daily_summary_table(start_date, end_date, cluster_id)
return (start_date, end_date)
示例3: test_upsert_monthly_cluster_cost_line_item
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def test_upsert_monthly_cluster_cost_line_item(self):
"""Test that the cluster monthly costs are not updated."""
report_table_name = OCP_REPORT_TABLE_MAP["report"]
report_table = getattr(self.accessor.report_schema, report_table_name)
rate = 1000
with schema_context(self.schema):
report_entry = report_table.objects.all().aggregate(Min("interval_start"), Max("interval_start"))
start_date = report_entry["interval_start__min"]
end_date = report_entry["interval_start__max"]
start_date = str(self.reporting_period.report_period_start)
end_date = str(self.reporting_period.report_period_end)
self.accessor.upsert_monthly_cluster_cost_line_item(
start_date, end_date, self.cluster_id, "cluster_alias", metric_constants.SUPPLEMENTARY_COST_TYPE, rate
)
summary_table_name = OCP_REPORT_TABLE_MAP["line_item_daily_summary"]
query = self.accessor._get_db_obj_query(summary_table_name)
self.assertEqual(query.filter(cluster_id=self.cluster_id).first().supplementary_monthly_cost, rate)
示例4: test_upsert_monthly_cluster_cost_line_item_no_report_period
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def test_upsert_monthly_cluster_cost_line_item_no_report_period(self):
"""Test that the cluster monthly costs are not updated when no report period is found."""
report_table_name = OCP_REPORT_TABLE_MAP["report"]
report_table = getattr(self.accessor.report_schema, report_table_name)
rate = 1000
with schema_context(self.schema):
report_entry = report_table.objects.all().aggregate(Min("interval_start"), Max("interval_start"))
start_date = report_entry["interval_start__min"]
end_date = report_entry["interval_start__max"]
start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0)
end_date = end_date.replace(hour=0, minute=0, second=0, microsecond=0)
self.accessor.upsert_monthly_cluster_cost_line_item(
start_date, end_date, self.cluster_id, "cluster_alias", metric_constants.SUPPLEMENTARY_COST_TYPE, rate
)
summary_table_name = OCP_REPORT_TABLE_MAP["line_item_daily_summary"]
query = self.accessor._get_db_obj_query(summary_table_name)
self.assertFalse(query.filter(cluster_id=self.cluster_id).exists())
示例5: test_populate_markup_cost_no_billsids
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [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)
示例6: test_populate_markup_cost_no_billsids
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [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)
示例7: __iter__
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def __iter__(self):
times = sorted(
set(itertools.chain(*self.slots_qs().values_list("start", "end")))
)
slots = Slot.objects.filter(pk__in=self.slots_qs().values("pk"))
slots = slots.annotate(
room_count=Count("slotroom"), order=Min("slotroom__room__order")
)
slots = slots.order_by("start", "order")
row = []
for time, next_time in pairwise(times):
row = {"time": time, "slots": []}
for slot in slots:
if slot.start == time:
slot.rowspan = TimeTable.rowspan(
times, slot.start, slot.end
)
slot.colspan = slot.room_count
row["slots"].append(slot)
if row["slots"] or next_time is None:
yield row
示例8: copy_pub_date_to_date_sent
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def copy_pub_date_to_date_sent(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
Message = apps.get_model('zerver', 'Message')
if not Message.objects.exists():
# Nothing to do
return
first_uncopied_id = Message.objects.filter(date_sent__isnull=True,
).aggregate(Min('id'))['id__min']
# Note: the below id can fall in a segment
# where date_sent = pub_date already, but it's not a big problem
# this will just do some redundant UPDATEs.
last_id = Message.objects.latest("id").id
id_range_lower_bound = first_uncopied_id
id_range_upper_bound = first_uncopied_id + BATCH_SIZE
while id_range_upper_bound <= last_id:
sql_copy_pub_date_to_date_sent(id_range_lower_bound, id_range_upper_bound)
id_range_lower_bound = id_range_upper_bound + 1
id_range_upper_bound = id_range_lower_bound + BATCH_SIZE
time.sleep(0.1)
if last_id > id_range_lower_bound:
# Copy for the last batch.
sql_copy_pub_date_to_date_sent(id_range_lower_bound, last_id)
示例9: copy_id_to_bigid
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def copy_id_to_bigid(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
UserMessage = apps.get_model('zerver', 'UserMessage')
if not UserMessage.objects.exists():
# Nothing to do
return
# TODO: is the below lookup fast enough, considering there's no index on bigint_id?
first_uncopied_id = UserMessage.objects.filter(bigint_id__isnull=True,
).aggregate(Min('id'))['id__min']
# Note: the below id can fall in a segment
# where bigint_id = id already, but it's not a big problem
# this will just do some redundant UPDATEs.
last_id = UserMessage.objects.latest("id").id
id_range_lower_bound = first_uncopied_id
id_range_upper_bound = first_uncopied_id + BATCH_SIZE
while id_range_upper_bound <= last_id:
sql_copy_id_to_bigint_id(id_range_lower_bound, id_range_upper_bound)
id_range_lower_bound = id_range_upper_bound + 1
id_range_upper_bound = id_range_lower_bound + BATCH_SIZE
time.sleep(0.1)
if last_id > id_range_lower_bound:
# Copy for the last batch.
sql_copy_id_to_bigint_id(id_range_lower_bound, last_id)
示例10: get_queue_status
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def get_queue_status(self):
"""Returns the current status of the queue with statistics broken down by job type.
:returns: A list of each job type with calculated statistics.
:rtype: list[:class:`queue.models.QueueStatus`]
"""
status_dicts = Queue.objects.values(*['job_type__%s' % f for f in JobType.BASE_FIELDS])
status_dicts = status_dicts.annotate(count=models.Count('job_type'), longest_queued=models.Min('queued'),
highest_priority=models.Min('priority'))
status_dicts = status_dicts.order_by('job_type__is_paused', 'highest_priority', 'longest_queued')
# Convert each result to a real job type model with added statistics
results = []
for status_dict in status_dicts:
job_type_dict = {f: status_dict['job_type__%s' % f] for f in JobType.BASE_FIELDS}
job_type = JobType(**job_type_dict)
status = QueueStatus(job_type, status_dict['count'], status_dict['longest_queued'],
status_dict['highest_priority'])
results.append(status)
return results
示例11: inactive_ai_patients_filter
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def inactive_ai_patients_filter(qs):
'''Build a queryset of patients for those that have active action
items due in the future.
'''
future_ai_pts = coremodels.Patient.objects.filter(
actionitem__in=coremodels.ActionItem.objects
.filter(due_date__gt=django.utils.timezone.now().date())
.filter(completion_date=None)
.select_related('patient')
).annotate(soonest_due_date=Min('actionitem__due_date'))
future_referral_pts = coremodels.Patient.objects.filter(
followuprequest__in=referrals.FollowupRequest.objects
.filter(due_date__gt=django.utils.timezone.now().date())
.filter(completion_date=None)
.select_related('patient')
).annotate(soonest_due_date=Min('followuprequest__due_date'))
out_list = merge_pt_querysets_by_soonest_date(future_ai_pts, future_referral_pts)
return out_list
示例12: get_context_data
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def get_context_data(self, **kwargs):
context = super(UserPage, self).get_context_data(**kwargs)
context['hide_solved'] = int(self.hide_solved)
context['authored'] = self.object.authored_problems.filter(is_public=True, is_organization_private=False) \
.order_by('code')
rating = self.object.ratings.order_by('-contest__end_time')[:1]
context['rating'] = rating[0] if rating else None
context['rank'] = Profile.objects.filter(
is_unlisted=False, performance_points__gt=self.object.performance_points,
).count() + 1
if rating:
context['rating_rank'] = Profile.objects.filter(
is_unlisted=False, rating__gt=self.object.rating,
).count() + 1
context['rated_users'] = Profile.objects.filter(is_unlisted=False, rating__isnull=False).count()
context.update(self.object.ratings.aggregate(min_rating=Min('rating'), max_rating=Max('rating'),
contests=Count('contest')))
return context
示例13: get
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def get(self, request, *args, **kwargs):
qs = self.get_queryset()
data = list(qs)
max_value = qs.aggregate(m=Max('count'))['m']
min_date = qs.aggregate(m=Min('date'))['m']
max_date = qs.aggregate(m=Max('date'))['m']
for item in data:
item['weight'] = item['count'] / max_value
# TODO: update url
item['url'] = '{}?date_search={}'.format(
reverse('extract:date-usage-list'), item['date'].isoformat())
ret = {'data': data,
'min_year': min_date.year,
'max_year': max_date.year,
'context': self.get_context()}
return JsonResponse(ret)
示例14: remove_duplicate_renditions
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def remove_duplicate_renditions(apps, schema_editor):
Rendition = apps.get_model('wagtailimages.Rendition')
# Find all filter_id / image_id pairings that appear multiple times in the renditions table
# with focal_point_key = NULL
duplicates = (
Rendition.objects.filter(focal_point_key__isnull=True).
values('image_id', 'filter_id').
annotate(count_id=models.Count('id'), min_id=models.Min('id')).
filter(count_id__gt=1)
)
# Delete all occurrences of those pairings, except for the one with the lowest ID
for duplicate in duplicates:
Rendition.objects.filter(
focal_point_key__isnull=True,
image=duplicate['image_id'],
filter=duplicate['filter_id']
).exclude(
id=duplicate['min_id']
).delete()
示例15: threads
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Min [as 别名]
def threads(request):
page = int(request.GET.get('p', 0))
paging_size = settings.PAGING_SIZE
tree = Comment.objects.filter( tree_id=OuterRef('tree_id'), user=OuterRef('user')).values('tree_id', 'user__pk').annotate(min_level=Min('level')).order_by()
stories = Comment.objects.filter(
user=request.user
).filter(
Q(level__in=Subquery(tree.values('min_level'), output_field=models.IntegerField())) # TODO: level= or level__in= ???
).select_related(
'user', 'parent', 'to_story'
).order_by(
'-created_at'
)[(page*paging_size):(page+1)*(paging_size)]
if len(stories) < 1 and page != 0:
back = _one_page_back(request)
if back:
return back
return render(request, 'news/index.html', {'stories': stories, 'hide_text':False, 'page': page, 'rank_start': None, 'show_children': True})