本文整理汇总了Python中django.db.models.OuterRef方法的典型用法代码示例。如果您正苦于以下问题:Python models.OuterRef方法的具体用法?Python models.OuterRef怎么用?Python models.OuterRef使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.OuterRef方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: populate_labelling_msg_fields
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [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")
示例2: threads
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [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})
示例3: get
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [as 别名]
def get(self, request) :
if not request.user.is_authenticated:
thing_list = Thing.objects.all()
else:
thing_list = Thing.objects.annotate(
FAV_USER_ID=Exists(Fav.objects.filter(user=self.request.user,thing_id=OuterRef('id')))
).all()
ctx = {'thing_list' : thing_list}
return render(request, self.template_name, ctx)
# https://stackoverflow.com/questions/2314920/django-show-log-orm-sql-calls-from-python-shell
# pip install django-extensions
# ./manage.py shell_plus --print-sql
# Below this line, we see raw sql... With great power comes great responsibility
# https://docs.djangoproject.com/en/3.0/topics/db/sql/
# A List view using raw SQL - super efficient
示例4: all_latest
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [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
示例5: test_orders_nulls_first_on_filtered_subquery
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [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],
)
示例6: get_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [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
示例7: handle
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [as 别名]
def handle(self, *args, **options):
qs = AutoRating.objects.filter(deadline__gt=timezone.now())
qs = qs.select_related('party')
qs = qs.prefetch_related('party__rating_set')
for auto_rating in tqdm.tqdm(qs, desc='update auto rating'):
party = auto_rating.party
contests = Contest.objects.filter(**auto_rating.info['filter'])
party_contests = party.rating_set.filter(contest_id=OuterRef('pk'))
contests = contests.annotate(in_party=Exists(party_contests)).filter(in_party=False)
for contest in contests:
rating = Rating(party=party, contest=contest)
rating.save()
示例8: handle
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [as 别名]
def handle(self, *args, **options):
self.stdout.write(str(options))
args = AttrDict(options)
if args.resources:
if len(args.resources) == 1:
contests = Contest.objects.filter(resource__module__resource__host__iregex=args.resources[0])
else:
resources = [Resource.objects.get(host__iregex=r) for r in args.resources]
contests = Contest.objects.filter(resource__module__resource__host__in=resources)
else:
has_module = Module.objects.filter(resource_id=OuterRef('resource__pk'))
contests = Contest.objects.annotate(has_module=Exists(has_module)).filter(has_module=True)
if args.only_new:
has_statistics = Statistics.objects.filter(contest_id=OuterRef('pk'))
contests = contests.annotate(has_statistics=Exists(has_statistics)).filter(has_statistics=False)
if args.year:
contests = contests.filter(start_time__year=args.year)
self.parse_statistic(
contests=contests,
previous_days=args.days,
limit=args.limit,
with_check=not args.no_check_timing,
stop_on_error=args.stop_on_error,
random_order=args.random_order,
no_update_results=args.no_update_results,
freshness_days=args.freshness_days,
title_regex=args.event,
users=args.users,
with_stats=not args.no_stats,
update_without_new_rating=args.update_without_new_rating,
)
示例9: queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [as 别名]
def queryset(self, request, queryset):
if self.value() in ['yes', 'no']:
logins = Login.objects.filter(team=OuterRef('pk'), stage=OuterRef('status'))
queryset = queryset.annotate(has_login=Exists(logins))
queryset = queryset.filter(has_login=self.value() == 'yes')
return queryset
示例10: get_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [as 别名]
def get_queryset(self):
proj = self.get_content_object()
related_content_objs = ContentObject.objects.filter(
resource=OuterRef('id'),
content_type=ContentType.objects.get_for_model(proj),
object_id=proj.id)
return super().get_queryset().prefetch_related(
'content_objects__content_type').annotate(
attached=Exists(related_content_objs))
示例11: get_unfiltered_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [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 OuterRef [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: prepare_patches
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [as 别名]
def prepare_patches(request, m, max_depth=None):
if m.total_patches == 1:
return []
replies = m.get_replies().filter(is_patch=True)
commit_replies = api.models.Message.objects.filter(
in_reply_to=OuterRef("message_id")
)
replies = replies.annotate(has_replies=Exists(commit_replies))
project = m.project
return [prepare_message(request, project, x, True) for x in replies]
示例14: _get_series_for_diff
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [as 别名]
def _get_series_for_diff(self, q):
def _get_message_data(m):
filtered = ""
sep = ""
for l in m.get_body().splitlines():
for pat, repl in [
(r"^index [0-9a-f]+\.\.[0-9a-f]+", r"index XXXXXXX..XXXXXXX"),
(
r"^@@ -[0-9]+,[0-9]+ \+[0-9]+,[0-9]+ @@( |$)",
r"@@ -XXX,XX +XXX,XX @@\1",
),
]:
l = re.sub(pat, repl, l)
filtered += sep + l
sep = "\n"
return PatchInfo(
subject=m.subject,
link=m.get_message_view_url(),
has_replies=m.has_replies,
body=filtered,
)
def _add_has_replies(q, **kwargs):
replies = Message.objects.filter(
in_reply_to=OuterRef("message_id"), **kwargs
)
return q.annotate(has_replies=Exists(replies))
q = _add_has_replies(q, is_patch=False)
s = q.first()
ret = list()
data = _get_message_data(s)
ret.append(data)
if not s.is_patch:
for p in _add_has_replies(s.get_patches()):
data = _get_message_data(p)
ret.append(data)
return ret
示例15: stats
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OuterRef [as 别名]
def stats(request):
past_30_days = Render.objects.filter(
created_at__gt=datetime.datetime.today() - datetime.timedelta(days=30)
)
newest_renders = Render.objects.filter(paper=OuterRef("pk")).order_by("-created_at")
papers = Paper.objects.annotate(
last_render_state=Subquery(newest_renders.values("state")[:1])
).exclude(last_render_state=None)
return render(
request,
"papers/stats.html",
{
"total_renders": int(Render.objects.count()),
"successful_renders": int(
Render.objects.filter(state=Render.STATE_SUCCESS).count()
),
"failed_renders": int(
Render.objects.filter(state=Render.STATE_FAILURE).count()
),
"total_renders_30_days": int(past_30_days.count()),
"successful_renders_30_days": int(
past_30_days.filter(state=Render.STATE_SUCCESS).count()
),
"failed_renders_30_days": int(
past_30_days.filter(state=Render.STATE_FAILURE).count()
),
"total_papers": int(papers.count()),
"successful_papers": int(
papers.filter(last_render_state=Render.STATE_SUCCESS).count()
),
"failed_papers": int(
papers.filter(last_render_state=Render.STATE_FAILURE).count()
),
},
)