本文整理汇总了Python中django.db.models.Subquery方法的典型用法代码示例。如果您正苦于以下问题:Python models.Subquery方法的具体用法?Python models.Subquery怎么用?Python models.Subquery使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.Subquery方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _find_subqueries_in_where
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def _find_subqueries_in_where(children):
for child in children:
child_class = child.__class__
if child_class is WhereNode:
for grand_child in _find_subqueries_in_where(child.children):
yield grand_child
elif child_class is ExtraWhere:
raise IsRawQuery
elif child_class is NothingNode:
pass
else:
rhs = child.rhs
rhs_class = rhs.__class__
if rhs_class is Query:
yield rhs
elif rhs_class is QuerySet:
yield rhs.query
elif rhs_class is Subquery or rhs_class is Exists:
try:
yield rhs.query
except:
yield rhs.queryset.query
elif rhs_class in UNCACHABLE_FUNCS:
raise UncachableQuery
示例2: populate_labelling_msg_fields
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def populate_labelling_msg_fields(apps, schema_editor):
Labelling = apps.get_model("msgs", "Labelling")
Message = apps.get_model("msgs", "Message")
max_id = 0
num_updated = 0
while True:
id_batch = list(
Labelling.objects.filter(id__gt=max_id, message_created_on=None)
.values_list("id", flat=True)
.order_by("id")[:BATCH_SIZE]
)
if not id_batch:
break
Labelling.objects.filter(id__in=id_batch).update(
message_is_flagged=Subquery(Message.objects.filter(id=OuterRef("message_id")).values("is_flagged")[:1]),
message_is_archived=Subquery(Message.objects.filter(id=OuterRef("message_id")).values("is_archived")[:1]),
message_created_on=Subquery(Message.objects.filter(id=OuterRef("message_id")).values("created_on")[:1]),
)
max_id = id_batch[-1]
num_updated += len(id_batch)
print(f" > Updated {num_updated} instances of labelling")
示例3: get_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def get_queryset(self, term_id=None):
term_usages = TermUsage.objects.all()
self.read_request_filters()
if hasattr(self, 'term_filter'):
filter_val = self.term_filter[0]['value']
term_usages = TermUsage.objects.filter(term__term__startswith=filter_val)
term_usages = term_usages.order_by()
qs = TextUnit.objects.only('pk', 'document_id', 'unit_type', 'language',
'location_start', 'location_end').filter(
pk__in=Subquery(term_usages.values('text_unit_id'))).order_by('document_id')
filtered_projects = self.request.user.userprojectssavedfilter.projects.all()
if filtered_projects:
qs = qs.filter(document__project_id__in=filtered_projects)
else:
qs = self.filter_count_predicate(qs)
return qs
示例4: threads
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [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})
示例5: all_latest
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def all_latest(self) -> Dict[str, ModuleZipfile]:
"""
Return all modules, unordered, indexed by ID.
"""
# https://docs.djangoproject.com/en/2.2/ref/models/expressions/#subquery-expressions
latest = Subquery(
(
DbModuleVersion.objects.filter(id_name=OuterRef("id_name"))
.order_by("-last_update_time")
.values("id")
)[:1]
)
db_modules = list(
DbModuleVersion.objects.annotate(_latest=latest).filter(id=F("_latest"))
)
ret = dict(StaticModuleLookup) # fallback modules (TODO nix all static modules)
ret.update({m.id_name: self._download_or_reuse_zipfile(m) for m in db_modules})
return ret
示例6: test_orders_nulls_first_on_filtered_subquery
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def test_orders_nulls_first_on_filtered_subquery(self):
Article.objects.filter(headline='Article 1').update(author=self.author_1)
Article.objects.filter(headline='Article 2').update(author=self.author_1)
Article.objects.filter(headline='Article 4').update(author=self.author_2)
Author.objects.filter(name__isnull=True).delete()
author_3 = Author.objects.create(name='Name 3')
article_subquery = Article.objects.filter(
author=OuterRef('pk'),
headline__icontains='Article',
).order_by().values('author').annotate(
last_date=Max('pub_date'),
).values('last_date')
self.assertQuerysetEqualReversible(
Author.objects.annotate(
last_date=Subquery(article_subquery, output_field=DateTimeField())
).order_by(
F('last_date').asc(nulls_first=True)
).distinct(),
[author_3, self.author_1, self.author_2],
)
示例7: filter_owners_name
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def filter_owners_name(self, queryset, name, value):
"""Filter queryset by owner's name."""
result = queryset.model.objects.none()
user_subquery = self._get_user_subquery(value)
for user in user_subquery:
result = result.union(
get_objects_for_user(
user, self.owner_permission, queryset, with_superuser=False
)
)
# Union can no longer be filtered, so we have to create a new queryset
# for following filters.
return result.model.objects.filter(pk__in=Subquery(result.values("pk")))
示例8: get_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def get_queryset(self):
from timed.employment.models import PublicHoliday
queryset = super().get_queryset()
queryset = queryset.exclude(
date__in=models.Subquery(
PublicHoliday.objects.filter(
location__employments__user=models.OuterRef("user")
).values("date")
)
)
return queryset
示例9: get_next_expression
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def get_next_expression(self, model_instance):
""" Generate an expression that will evaluate to the next valid ordering value """
# This will be the next number larger than existing records in the ordering set
# If no records in the ordering set, start from 0
# Evade any custom model managers
qs = models.QuerySet(self.model).filter(**self.get_filter_kwargs_for_object(model_instance))
qs = qs.annotate(_next=Max(self.attname) + 1).values('_next').order_by()
# Hackishly clip group_by clause to guarantee single result
qs.query.group_by = []
return BypassExpression(Coalesce(Subquery(qs), 0, output_field=models.IntegerField()))
示例10: _get_tables
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def _get_tables(db_alias, query):
if query.select_for_update or (
not cachalot_settings.CACHALOT_CACHE_RANDOM
and '?' in query.order_by):
raise UncachableQuery
try:
if query.extra_select:
raise IsRawQuery
# Gets all tables already found by the ORM.
tables = set(query.table_map)
tables.add(query.get_meta().db_table)
# Gets tables in subquery annotations.
for annotation in query.annotations.values():
if isinstance(annotation, Subquery):
# Django 2.2+ removed queryset in favor of simply using query
try:
tables.update(_get_tables(db_alias, annotation.queryset.query))
except AttributeError:
tables.update(_get_tables(db_alias, annotation.query))
# Gets tables in WHERE subqueries.
for subquery in _find_subqueries_in_where(query.where.children):
tables.update(_get_tables(db_alias, subquery))
# Gets tables in HAVING subqueries.
if isinstance(query, AggregateQuery):
tables.update(
_get_tables_from_sql(connections[db_alias], query.subquery))
# Gets tables in combined queries
# using `.union`, `.intersection`, or `difference`.
if query.combined_queries:
for combined_query in query.combined_queries:
tables.update(_get_tables(db_alias, combined_query))
except IsRawQuery:
sql = query.get_compiler(db_alias).as_sql()[0].lower()
tables = _get_tables_from_sql(connections[db_alias], sql)
if not are_all_cachable(tables):
raise UncachableQuery
return tables
示例11: get_unfiltered_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def get_unfiltered_queryset(self):
latest_rating_subquery = Rating.objects.filter(user=OuterRef('pk')).order_by('-contest__end_time')
return (
Profile.objects
.filter(is_unlisted=False, user__is_active=True)
.annotate(
username=F('user__username'),
latest_rating=Subquery(latest_rating_subquery.values('rating')[:1]),
latest_volatility=Subquery(latest_rating_subquery.values('volatility')[:1]),
)
.order_by('id')
.only('id', 'points', 'performance_points', 'problem_count', 'display_rank')
)
示例12: update_participation
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def update_participation(self, participation):
cumtime = 0
score = 0
format_data = {}
queryset = (participation.submissions.values('problem_id')
.filter(points=Subquery(
participation.submissions.filter(problem_id=OuterRef('problem_id'))
.order_by('-points').values('points')[:1]))
.annotate(time=Min('submission__date'))
.values_list('problem_id', 'time', 'points'))
for problem_id, time, points in queryset:
if self.config['cumtime']:
dt = (time - participation.start).total_seconds()
if points:
cumtime += dt
else:
dt = 0
format_data[str(problem_id)] = {'points': points, 'time': dt}
score += points
participation.cumtime = max(cumtime, 0)
participation.score = score
participation.tiebreaker = 0
participation.format_data = format_data
participation.save()
示例13: get_app_config_dump
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def get_app_config_dump(document_type_codes=None) -> str:
object_handler_by_model = {DocumentField: clear_owner}
filter_by_model = {}
if document_type_codes:
def document_field_filter(qs):
return qs.filter(document_type__code__in=document_type_codes)
category_document_type_field = document_field_filter(DocumentField.objects.get_queryset()) \
.values_list('category__pk') \
.distinct('category__pk') \
.order_by('category__pk')
field_family_document_type_field = document_field_filter(DocumentField.objects.get_queryset()) \
.values_list('family__pk') \
.distinct('family__pk') \
.order_by('family__pk')
filter_by_model = dict(APP_CONFIG_MODELS)
filter_by_model.update({
DocumentType: lambda qs: qs.filter(code__in=document_type_codes),
DocumentField: document_field_filter,
DocumentFieldDetector: lambda qs: qs.filter(field__document_type__code__in=document_type_codes),
DocumentFieldCategory: lambda qs: qs.filter(pk__in=Subquery(category_document_type_field)),
DocumentFieldFamily: lambda qs: qs.filter(pk__in=Subquery(field_family_document_type_field))
})
return get_dump(filter_by_model, object_handler_by_model)
示例14: qs_admins_and_managers
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def qs_admins_and_managers(self) -> models.QuerySet:
return self.filter(role__in=models.Subquery(Role.objects.qs_admins_or_managers().order_by().values_list('pk')))
示例15: update
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Subquery [as 别名]
def update(self, instance: Document, validated_data):
with transaction.atomic():
system_fields_changed = list()
new_status = validated_data.get('status')
if new_status is not None and new_status.pk != instance.status_id:
is_active = instance.status and instance.status.is_active
if new_status.is_active != is_active:
field_ids = self.field_repo.get_doc_field_ids_with_values(instance.pk)
DocumentField.objects \
.filter(document_type_id=instance.document_type_id, pk__in=Subquery(field_ids)) \
.update(dirty=True)
system_fields_changed.append(DocumentSystemField.status.value)
user = self.context['request'].user # type: User
new_assignee = validated_data.get('assignee')
prev_assignee = instance.assignee
if new_assignee is None and prev_assignee is not None:
validated_data['assign_date'] = None
system_fields_changed.append(DocumentSystemField.assignee.value)
elif new_assignee is not None and (prev_assignee is None or new_assignee.pk != prev_assignee.pk):
validated_data['assign_date'] = datetime.datetime.now(tz=user.get_time_zone())
system_fields_changed.append(DocumentSystemField.assignee.value)
res = super().update(instance, validated_data)
plan_process_document_changed(doc_id=instance.pk,
system_fields_changed=system_fields_changed,
generic_fields_changed=False,
user_fields_changed=False,
changed_by_user_id=user.pk)
return res