本文整理汇总了Python中django.db.models.Count方法的典型用法代码示例。如果您正苦于以下问题:Python models.Count方法的具体用法?Python models.Count怎么用?Python models.Count使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.Count方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: show_stats
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def show_stats(**kwargs):
"""
Shows badges stats.
"""
db_read = kwargs.get('db_read', DEFAULT_DB_ALIAS)
badges = (Badge.objects.using(db_read)
.all()
.annotate(u_count=Count('users'))
.order_by('u_count'))
for badge in badges:
logger.info('{:<20} {:>10} users awarded | users_count: {})'.format(
badge.name,
badge.u_count,
badge.users_count))
示例2: spending_over_time
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def spending_over_time(self, request):
fiscal_year = request.query_params.get("fiscal_year")
queryset = self.filter_queryset(self.get_queryset())
if fiscal_year:
start_date, end_date = get_fiscal_year_range(int(fiscal_year))
queryset = queryset.filter(
date_of_grant__gte=start_date, date_of_grant__lte=end_date
)
queryset = (
queryset.without_amendments()
.annotate(month=TruncMonth("date_of_grant"))
.values("month")
.annotate(total=Sum("amount_to_pay"), count=Count("id"))
.values("month", "total", "count")
.order_by("month")
)
return Response(queryset)
示例3: filter_entities
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def filter_entities(self, queryset, name, value):
if not value:
return queryset
return (
queryset.filter(contract__entity__in=value)
.distinct()
.annotate(
contracts_total=Sum(
"contract__amount_to_pay",
filter=Q(contract__parent=None, contract__entity__in=value),
),
contracts_count=Count(
"contract",
filter=Q(contract__parent=None, contract__entity__in=value),
),
)
)
示例4: filter_entity_by_id
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def filter_entity_by_id(self, queryset, name, value):
if not value:
return queryset
return (
queryset.filter(contract__entity_id__in=value)
.distinct()
.annotate(
contracts_total=Sum(
"contract__amount_to_pay",
filter=Q(contract__parent=None, contract__entity_id__in=value),
),
contracts_count=Count(
"contract",
filter=Q(contract__parent=None, contract__entity_id__in=value),
),
)
)
示例5: filter_contractors_by_id
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def filter_contractors_by_id(self, queryset, name, value):
if not value:
return queryset
contracts = Contract.objects.filter(contractors__in=value).only("id")
return (
queryset.filter(contract__in=contracts)
.distinct()
.annotate(
contracts_total=Sum(
"contract__amount_to_pay",
filter=Q(contract__parent=None, contract__in=contracts),
),
contracts_count=Count(
"contract", filter=Q(contract__parent=None, contract__in=contracts)
),
)
)
示例6: test_execute_query_ocp_aws_costs_group_by_project
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def test_execute_query_ocp_aws_costs_group_by_project(self):
"""Test that grouping by project filters data."""
with tenant_context(self.tenant):
# Force Django to do GROUP BY to get nodes
projects = (
OCPAWSCostLineItemDailySummary.objects.filter(usage_start__gte=self.ten_days_ago)
.values(*["namespace"])
.annotate(project_count=Count("namespace"))
.all()
)
project_of_interest = projects[0].get("namespace")
url = reverse("reports-openshift-aws-costs")
client = APIClient()
params = {"group_by[project]": project_of_interest}
url = url + "?" + urlencode(params, quote_via=quote_plus)
response = client.get(url, **self.headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
for entry in data.get("data", []):
for project in entry.get("projects", []):
self.assertEqual(project.get("project"), project_of_interest)
示例7: test_execute_query_ocp_aws_instance_type_by_project
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def test_execute_query_ocp_aws_instance_type_by_project(self):
"""Test that the instance type API runs when grouped by project."""
with tenant_context(self.tenant):
# Force Django to do GROUP BY to get nodes
projects = (
OCPAWSCostLineItemDailySummary.objects.filter(usage_start__gte=self.ten_days_ago)
.values(*["namespace"])
.annotate(project_count=Count("namespace"))
.all()
)
self.assertNotEqual(len(projects), 0)
project_of_interest = projects[0].get("namespace")
url = reverse("reports-openshift-aws-instance-type")
client = APIClient()
params = {"group_by[project]": project_of_interest}
url = url + "?" + urlencode(params, quote_via=quote_plus)
response = client.get(url, **self.headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
for entry in data.get("data", []):
for project in entry.get("projects", []):
self.assertEqual(project.get("project"), project_of_interest)
示例8: test_execute_query_group_by_project
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def test_execute_query_group_by_project(self):
"""Test that grouping by project filters data."""
with tenant_context(self.tenant):
# Force Django to do GROUP BY to get nodes
projects = (
OCPUsageLineItemDailySummary.objects.filter(usage_start__gte=self.ten_days_ago.date())
.values(*["namespace"])
.annotate(project_count=Count("namespace"))
.all()
)
project_of_interest = projects[0].get("namespace")
url = reverse("reports-openshift-cpu")
client = APIClient()
params = {"group_by[project]": project_of_interest}
url = url + "?" + urlencode(params, quote_via=quote_plus)
response = client.get(url, **self.headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
for entry in data.get("data", []):
for project in entry.get("projects", []):
self.assertEqual(project.get("project"), project_of_interest)
示例9: test_execute_query_group_by_cluster
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def test_execute_query_group_by_cluster(self):
"""Test that grouping by cluster filters data."""
with tenant_context(self.tenant):
# Force Django to do GROUP BY to get nodes
clusters = (
OCPUsageLineItemDailySummary.objects.filter(usage_start__gte=self.ten_days_ago.date())
.values(*["cluster_id"])
.annotate(cluster_count=Count("cluster_id"))
.all()
)
cluster_of_interest = clusters[0].get("cluster_id")
url = reverse("reports-openshift-cpu")
client = APIClient()
params = {"group_by[cluster]": cluster_of_interest}
url = url + "?" + urlencode(params, quote_via=quote_plus)
response = client.get(url, **self.headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
for entry in data.get("data", []):
for cluster in entry.get("clusters", []):
self.assertEqual(cluster.get("cluster"), cluster_of_interest)
示例10: test_execute_query_group_by_node
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def test_execute_query_group_by_node(self):
"""Test that grouping by node filters data."""
with tenant_context(self.tenant):
# Force Django to do GROUP BY to get nodes
nodes = (
OCPUsageLineItemDailySummary.objects.values(*["node"])
.filter(usage_start__gte=self.ten_days_ago.date())
.values(*["node"])
.annotate(node_count=Count("node"))
.all()
)
node_of_interest = nodes[0].get("node")
url = reverse("reports-openshift-cpu")
client = APIClient()
params = {"group_by[node]": node_of_interest}
url = url + "?" + urlencode(params, quote_via=quote_plus)
response = client.get(url, **self.headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
for entry in data.get("data", []):
for node in entry.get("nodes", []):
self.assertIn(node.get("node"), node_of_interest)
示例11: filter_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [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')
示例12: filter_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [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.select_related('xf', 'em')
else:
project_id = get_object_or_404(Site, pk=pk).project.id
queryset = queryset.filter(Q(site__id=pk, from_project=False)
| Q (project__id=project_id))
return queryset.annotate(
site_response_count=Count("site_form_instances",),
response_count=Count(Case(
When(project__isnull=False, project_form_instances__site__id=pk, then=F('project_form_instances')),
output_field=IntegerField(),
), distinct=True)
).select_related('xf', 'em')
示例13: test_invalidate_aggregate
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def test_invalidate_aggregate(self):
with self.assertNumQueries(1):
self.assertEqual(User.objects.aggregate(n=Count('test'))['n'], 0)
with self.assertNumQueries(2 if self.is_dj_21_below_and_is_sqlite() else 1):
u = User.objects.create_user('test')
with self.assertNumQueries(1):
self.assertEqual(User.objects.aggregate(n=Count('test'))['n'], 0)
with self.assertNumQueries(2 if self.is_dj_21_below_and_is_sqlite() else 1):
Test.objects.create(name='test1')
with self.assertNumQueries(1):
self.assertEqual(User.objects.aggregate(n=Count('test'))['n'], 0)
with self.assertNumQueries(2 if self.is_dj_21_below_and_is_sqlite() else 1):
Test.objects.create(name='test2', owner=u)
with self.assertNumQueries(1):
self.assertEqual(User.objects.aggregate(n=Count('test'))['n'], 1)
with self.assertNumQueries(2 if self.is_dj_21_below_and_is_sqlite() else 1):
Test.objects.create(name='test3')
with self.assertNumQueries(1):
self.assertEqual(User.objects.aggregate(n=Count('test'))['n'], 1)
示例14: calculate_karma
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def calculate_karma(self):
# CALCULATES THE KARMA POINT OF USER
# ACCORDING TO HOW MANY TIMES SUPPORTED * 2
# DECREASE BY FALLACY COUNT * 2
# HOW MANY CHILD PREMISES ARE ADDED TO USER'S PREMISES
karma = 0
support_sum = self.user_premises.aggregate(Count('supporters'))
karma += 2 * support_sum['supporters__count']
main_premises = self.user_premises.all()
all_sub_premises = []
for premise in main_premises:
all_sub_premises += premise.published_children().values_list('pk',
flat=True)
karma -= 2 * (premise.reports.count())
not_owned_sub_premises = Premise.objects.\
filter(id__in=all_sub_premises).\
exclude(user__id=self.id).count()
karma += not_owned_sub_premises
return karma
示例15: list_bulk_returns
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Count [as 别名]
def list_bulk_returns(request):
from django.db.models import Count
title = _("Browse Bulk Returns")
returns = Shipment.objects.exclude(dispatched_at=None).annotate(num_parts=Count('servicepart'))
page = request.GET.get("page")
returns = paginate(returns, page, 50)
counts = prep_counts()
return render(request, "shipments/list_bulk_returns.html", locals())