本文整理汇总了Python中django.db.models.When方法的典型用法代码示例。如果您正苦于以下问题:Python models.When方法的具体用法?Python models.When怎么用?Python models.When使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.When方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [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()
示例2: fix_index
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [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)
示例3: with_balances
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [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
示例4: with_transaction_balances
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [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
示例5: make_contest_ranking_profile
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [as 别名]
def make_contest_ranking_profile(contest, participation, contest_problems):
def display_user_problem(contest_problem):
# When the contest format is changed, `format_data` might be invalid.
# This will cause `display_user_problem` to error, so we display '???' instead.
try:
return contest.format.display_user_problem(participation, contest_problem)
except (KeyError, TypeError, ValueError):
return mark_safe('<td>???</td>')
user = participation.user
return ContestRankingProfile(
id=user.id,
user=user.user,
css_class=user.css_class,
username=user.username,
points=participation.score,
cumtime=participation.cumtime,
tiebreaker=participation.tiebreaker,
organization=user.organization,
participation_rating=participation.rating.rating if hasattr(participation, 'rating') else None,
problem_cells=[display_user_problem(contest_problem) for contest_problem in contest_problems],
result_cell=contest.format.display_participation_result(participation),
participation=participation,
)
示例6: validate_email
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [as 别名]
def validate_email(self):
"""Ensure emails are unique across the models tracking emails.
Since it's essential to keep email addresses unique to support our
workflows, a `ValidationError` will be raised if the email trying
to be saved is already assigned to some other user.
"""
lookup = Q(email__iexact=self.email)
if self.pk is not None:
# When there's an update, ensure no one else has this address
lookup &= ~Q(user=self)
try:
EmailAddress.objects.get(lookup)
except EmailAddress.DoesNotExist:
pass
else:
raise ValidationError({"email": [_("This email address already exists.")]})
示例7: pre_filter
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [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
示例8: get_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [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()
))
示例9: query_search
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [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
示例10: children
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [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
示例11: get_context_data
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [as 别名]
def get_context_data(self, **kwargs):
p = Proposal.objects.aggregate(
proposals=Count('pk'),
proposal_elab=Count(
Case(When(status='elab', then=1), output_field=IntegerField())),
proposal_pending=Count(
Case(When(status='p', then=1), output_field=IntegerField())),
proposal_concluded=Count(
Case(When(status='co', then=1), output_field=IntegerField())),
proposal_approved=Count(
Case(When(status='a', then=1), output_field=IntegerField())),
proposal_canceled=Count(
Case(When(status='c', then=1), output_field=IntegerField())),
)
context = super(Dashboard, self).get_context_data(**kwargs)
context['proposals'] = p
context['proposal_list'] = self.proposal_list()
context['proposal_elab'] = self.proposal_elab()
context['entrys'] = self.entry_list()
context['contract_total_per_month'] = self.contract_total_per_month()
context['contract_total_per_year'] = self.contract_total_per_year()
return context
示例12: get_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [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
示例13: viral_video_detail
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [as 别名]
def viral_video_detail(request, pk):
yesterday = now() - timedelta(days=1)
qs = ViralVideo.objects.annotate(
total_views=models.F("authenticated_views") + models.F("anonymous_views"),
label=models.Case(
models.When(total_views__gt=POPULAR_FROM, then=models.Value("popular")),
models.When(created__gt=yesterday, then=models.Value("new")),
default=models.Value("cool"),
output_field=models.CharField(),
),
)
# DEBUG: check the SQL query that Django ORM generates
logger.debug(f"Query: {qs.query}")
qs = qs.filter(pk=pk)
if request.user.is_authenticated:
qs.update(authenticated_views=models.F("authenticated_views") + 1)
else:
qs.update(anonymous_views=models.F("anonymous_views") + 1)
video = get_object_or_404(qs)
return render(request, "viral_videos/viral_video_detail.html", {"video": video})
示例14: get_aggregate_engagement_data
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [as 别名]
def get_aggregate_engagement_data(self, course_id):
seven_days_ago = now() - datetime.timedelta(days=7)
dict_list = [
('videos_overall', When(entity_type='video', then='count')),
('videos_last_week', When(entity_type='video', created__gt=seven_days_ago, then=1)),
('problems_overall', When(entity_type='problem', then='count')),
('problems_last_week', When(entity_type='problem', created__gt=seven_days_ago, then='count')),
('correct_problems_overall', When(entity_type='problem', event='completed', then='count')),
('correct_problems_last_week', When(entity_type='problem', event='completed',
created__gt=seven_days_ago, then='count')),
('problems_attempts_overall', When(entity_type='problem', event='attempted', then='count')),
('problems_attempts_last_week', When(entity_type='problem', event='attempted',
created__gt=seven_days_ago, then='count')),
('forum_posts_overall', When(entity_type='discussion', then='count')),
('forum_posts_last_week', When(entity_type='discussion', created__gt=seven_days_ago, then='count')),
]
dict_parameters = {key: Sum(Case(val, output_field=IntegerField())) for key, val in dict_list}
dict_parameters['date_last_active'] = Max('created')
query = ModuleEngagement.objects.filter(course_id=course_id)\
.values('username')\
.annotate(**dict_parameters)
return query
示例15: package_list
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import When [as 别名]
def package_list(request, template_name="package/package_grid.html"):
context = {
'categories': [
{
"title_plural": category.title_plural,
"count": category.project_count,
"description": category.description,
"packages": category.project_set.published().order_by("-repo_watchers", "name")
}
for category in Category.objects.annotate(
project_count=Count(Case(When(project__is_published=True, then=1)))
)
]
}
return render(request, template_name, context)