本文整理匯總了Python中django.db.models.Case方法的典型用法代碼示例。如果您正苦於以下問題:Python models.Case方法的具體用法?Python models.Case怎麽用?Python models.Case使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.db.models
的用法示例。
在下文中一共展示了models.Case方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: filter_queryset
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [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')
示例2: filter_queryset
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [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')
示例3: get_for_site
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [as 別名]
def get_for_site(cls, handle, site, fall_back_to_default_site_menus=False):
"""Return a FlatMenu instance with a matching ``handle`` for the
provided ``site``, or for the default site (if suitable). If no
match is found, returns None."""
queryset = cls.objects.filter(handle__exact=handle)
site_q = Q(site=site)
if fall_back_to_default_site_menus:
site_q |= Q(site__is_default_site=True)
queryset = queryset.filter(site_q)
# return the best match or None
return queryset.annotate(matched_provided_site=Case(
When(site_id=site.id, then=1), default=0,
output_field=BooleanField()
)).order_by('-matched_provided_site').first()
示例4: populate_tracking_fields
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [as 別名]
def populate_tracking_fields(apps, schema_editor):
managers = [
apps.get_model('hosting', 'Phone')._default_manager.all(),
apps.get_model('hosting', 'Place')._default_manager.all(),
apps.get_model('hosting', 'Profile')._default_manager.all(),
apps.get_model('hosting', 'Website')._default_manager.all(),
]
for objects in managers:
objects.update(
deleted_on=Case(
When(deleted=False, then=None),
default=F('modified'),
output_field=DateTimeField())
)
objects.update(
checked_on=Case(
When(checked=False, then=None),
default=F('modified'),
output_field=DateTimeField())
)
示例5: get_queryset
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [as 別名]
def get_queryset(self):
try:
validity_period = SiteConfiguration.get_solo().confirmation_validity_period
except DatabaseError:
from datetime import timedelta
validity_period = timedelta(weeks=42)
validity_start = timezone.now() - validity_period
return super().get_queryset().annotate(deleted=Case(
When(deleted_on__isnull=True, then=False),
default=True,
output_field=BooleanField()
)).annotate(confirmed=Case(
When(confirmed_on__isnull=True, then=False),
When(confirmed_on__lt=validity_start, then=False),
default=True,
output_field=BooleanField()
)).annotate(checked=Case(
When(checked_on__isnull=True, then=False),
# When(checked_on__lt=validity_start, then=False), # Temporarily disabled.
default=True,
output_field=BooleanField()
)).select_related()
示例6: fix_index
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [as 別名]
def fix_index(request):
suggestion_list = Suggestion.objects.select_related('work', 'user').prefetch_related(
'work__category', 'evidence_set__user').annotate(
count_agrees=Count(Case(When(evidence__agrees=True, then=1))),
count_disagrees=Count(Case(When(evidence__agrees=False, then=1)))
).all().order_by('is_checked', '-date')
paginator = Paginator(suggestion_list, FIXES_PER_PAGE)
page = request.GET.get('page')
try:
suggestions = paginator.page(page)
except PageNotAnInteger:
suggestions = paginator.page(1)
except EmptyPage:
suggestions = paginator.page(paginator.num_pages)
context = {
'suggestions': suggestions
}
return render(request, 'fix/fix_index.html', context)
示例7: redirect_staff
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [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)
示例8: with_balances
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [as 別名]
def with_balances(self):
qs = self.annotate(
balances_debit=models.Sum(
models.Case(
models.When(
~models.Q(bookings__debit_account=None), then="bookings__amount"
),
default=0,
output_field=models.DecimalField(max_digits=8, decimal_places=2),
)
),
balances_credit=models.Sum(
models.Case(
models.When(
~models.Q(bookings__credit_account=None),
then="bookings__amount",
),
default=0,
output_field=models.DecimalField(max_digits=8, decimal_places=2),
)
),
)
return qs
示例9: with_transaction_balances
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [as 別名]
def with_transaction_balances(self):
qs = self.annotate(
transaction_balances_debit=models.Sum(
models.Case(
models.When(
~models.Q(transaction__bookings__debit_account=None),
then="transaction__bookings__amount",
),
default=0,
output_field=models.DecimalField(max_digits=8, decimal_places=2),
)
),
transaction_balances_credit=models.Sum(
models.Case(
models.When(
~models.Q(transaction__bookings__credit_account=None),
then="transaction__bookings__amount",
),
default=0,
output_field=models.DecimalField(max_digits=8, decimal_places=2),
)
),
)
return qs
示例10: get
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [as 別名]
def get(cls, as_dataframe: bool = True, **filter_kwargs):
"""
Return grouped by method/name statistic with AVG time and N calls
:param as_dataframe: bool - whether return pandas.dataframe or plain QuerySet
:param filter_kwargs: positional arguments represents options for filter() qs method
:return: pandas Dataframe OR QuerySet
"""
# .filter(has_error=False)\
qs = cls.objects\
.values('method', 'path', 'name')\
.annotate(calls=Count('id'),
errors=Count(Case(
When(has_error=True, then=1),
output_field=IntegerField(),
)),
avg_time=Avg('time'), max_time=Max('time'))\
.filter(**filter_kwargs)
qs = list(qs)
qs.sort(key=lambda m: -m['calls'])
if as_dataframe:
return pd.DataFrame.from_records(qs, columns=['name', 'method',
'calls', 'errors',
'avg_time', 'max_time'])
return qs
示例11: pre_filter
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [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
示例12: get_queryset
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [as 別名]
def get_queryset(self):
today = timezone.localdate()
return super() \
.get_queryset() \
.annotate(attendees_count=models.Count('attendee', distinct=True)) \
.annotate(last_date=models.Max('eventdate__date')) \
.annotate(activity_proposal_is_open=models.Case(
models.When(models.Q(limit_proposal_date__gte=today), then=True),
default=False,
output_field=models.BooleanField()
)) \
.annotate(registration_is_open=models.Case(
models.When(models.Q(last_date__gte=today), then=True),
default=False,
output_field=models.BooleanField()
))
示例13: query_search
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [as 別名]
def query_search( # pylint: disable=too-many-arguments
request, min_length, queryset, fields, collection, order_relevance=False):
"""Returns queryset with search filter."""
search = request.GET.get('query')
if search is not None and len(search) >= min_length:
# Use a FTS backend if we have one
if settings.USE_SONIC:
ids = run_query_sync(collection, search)
queryset = queryset.filter(id__in=ids)
# Preserve order of returned results
if order_relevance:
preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(ids)])
queryset = queryset.order_by(preserved)
return queryset
# Fallback if we are so quiet ;)
return query_search_fallback(queryset, fields, search) # pragma: no cover
return queryset
示例14: children
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [as 別名]
def children(self):
user_ordering = self.SITES_ORDERING[self.sites_ordering]['ordering']
pages = WagtailSitePage.objects.live().filter(Q(path__startswith=self.path) | Q(in_cooperation_with=self))
# When ordering by `path`, the collaborations would either all be listed first or last
# depending on whether the collaborator(s) page(s) was created before or after this page.
# Adding an overwrite here so collaborations always appear last.
if self.sites_ordering == self.SITES_ORDERING_PATH:
pages = pages.annotate(
is_own=Case(
When(path__startswith=self.path, then=Value(True)),
default_value=Value(False),
output_field=models.BooleanField(),
)
).order_by('is_own', *user_ordering)
# When ordering alphabetically or by creation date,
# own sites and collaboration sites will be sorted together.
else:
pages = pages.order_by(*user_ordering)
return pages
示例15: get_queryset
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Case [as 別名]
def get_queryset(self):
if not (hasattr(self, '_queryset') and self._queryset):
base_queryset = super(ContactListView, self).get_queryset()
if self.request.GET.get('q'):
search_contacts = self.get_search_contacts()
preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(search_contacts)])
base_queryset = base_queryset.filter(
id__in=search_contacts
).order_by(preserved)
self._queryset = base_queryset.annotate(has_last_contact=Count('last_contact'))
sort = self.request.GET.get('s')
if sort == 'oldnew':
self._queryset = self._queryset.order_by('-has_last_contact','last_contact')
if sort == 'newold':
self._queryset = self._queryset.order_by('-has_last_contact','-last_contact')
if sort == 'za':
self._queryset = self._queryset.order_by('-name')
if sort == 'az':
self._queryset = self._queryset.order_by('name')
if not self.request.GET.get('q') and not sort:
self._queryset = self._queryset.order_by('-has_last_contact','-last_contact')
self._queryset = self._queryset.prefetch_related('tags')
return self._queryset