本文整理汇总了Python中django.db.models.Prefetch方法的典型用法代码示例。如果您正苦于以下问题:Python models.Prefetch方法的具体用法?Python models.Prefetch怎么用?Python models.Prefetch使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.Prefetch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_json_for_variant_tags
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def get_json_for_variant_tags(tags, add_variant_guids=True):
"""Returns a JSON representation of the given variant tags.
Args:
tag (object): Django models for the VariantTag.
Returns:
dict: json objects
"""
def _process_result(tag_json, tag):
if add_variant_guids:
tag_json['variantGuids'] = [variant.guid for variant in tag.saved_variants.all()]
if add_variant_guids:
prefetch_related_objects(tags, Prefetch('saved_variants', queryset=SavedVariant.objects.only('guid')))
nested_fields = [{'fields': ('variant_tag_type', field), 'key': field} for field in ['name', 'category', 'color']]
return _get_json_for_models(tags, nested_fields=nested_fields, guid_key='tagGuid', process_result=_process_result)
示例2: get_json_for_variant_functional_data_tags
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def get_json_for_variant_functional_data_tags(tags, add_variant_guids=True):
"""Returns a JSON representation of the given variant tags.
Args:
tags (object): Django models for the VariantFunctionalData.
Returns:
dict: json objects
"""
def _process_result(tag_json, tag):
display_data = json.loads(tag.get_functional_data_tag_display())
tag_json.update({
'name': tag_json.pop('functionalDataTag'),
'metadataTitle': display_data.get('metadata_title'),
'color': display_data['color'],
})
if add_variant_guids:
tag_json['variantGuids'] = [variant.guid for variant in tag.saved_variants.all()]
if add_variant_guids:
prefetch_related_objects(tags, Prefetch('saved_variants', queryset=SavedVariant.objects.only('guid')))
return _get_json_for_models(tags, guid_key='tagGuid', process_result=_process_result)
示例3: get_json_for_variant_notes
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def get_json_for_variant_notes(notes, add_variant_guids=True):
"""Returns a JSON representation of the given variant notes.
Args:
notes (object): Django model for the VariantNote.
Returns:
dict: json objects
"""
def _process_result(note_json, note):
if add_variant_guids:
note_json['variantGuids'] = [variant.guid for variant in note.saved_variants.all()]
if add_variant_guids:
prefetch_related_objects(notes, Prefetch('saved_variants', queryset=SavedVariant.objects.only('guid')))
return _get_json_for_models(notes, guid_key='noteGuid', process_result=_process_result)
示例4: scan_scan_list
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def scan_scan_list(request: HttpRequest, scan_list_id: int) -> HttpResponse:
"""Schedule the scan of a scan list."""
scan_list = get_object_or_404(
ScanList.objects.prefetch_related(Prefetch(
'sites',
queryset=Site.objects.select_related('last_scan') \
.annotate_most_recent_scan_start() \
.annotate_most_recent_scan_end_or_null())
), pk=scan_list_id)
was_any_site_scannable = scan_list.scan()
if was_any_site_scannable:
num_scanning_sites = Scan.objects.filter(end__isnull=True).count()
messages.success(request,
_("Scans for this list have been scheduled. "+ \
"The total number of sites in the scanning queue "+ \
"is %i (including yours)." % num_scanning_sites))
else:
messages.warning(request,
_('All sites have been scanned recently. Please wait 30 minutes and try again.'))
return redirect(reverse('frontend:view_scan_list', args=(scan_list_id,)))
示例5: get_context_data
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
display_places = self.object.owned_places.filter(deleted=False)
if self.public_view:
display_places = display_places.filter(visibility__visible_online_public=True)
else:
family_members = Prefetch(
'family_members',
Profile.all_objects.order_by('birth_date').select_related('user'))
display_places = display_places.prefetch_related(family_members)
if self.request.user.has_perm(PERM_SUPERVISOR):
display_places = (display_places
.select_related('checked_by', 'checked_by__profile')
.defer('checked_by__profile__description'))
context['places'] = display_places.select_related('visibility')
display_phones = self.object.phones.filter(deleted=False)
context['phones'] = display_phones
context['phones_public'] = display_phones.filter(visibility__visible_online_public=True).select_related(None)
return context
示例6: get_default_events_query
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def get_default_events_query(event_q=None):
"""
Default events query that preloads all that will be needed in events_info()
Input:
event_q: An existing models.Event query
Return:
a query on models.Event
"""
if event_q == None:
event_q = models.Event.objects
jobs_q = models.Job.objects.select_related('config', 'recipe'
).prefetch_related('recipe__build_configs','recipe__depends_on',)
return event_q.order_by('-created').select_related(
'base__branch__repository__user__server',
'head__branch__repository__user__server',
'pull_request',
).prefetch_related(Prefetch('jobs', queryset=jobs_q))
示例7: get_user_repos_with_open_prs_status
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def get_user_repos_with_open_prs_status(username, last_modified=None):
"""
Get a list of open PRs for a user, grouped by repository and sorted by repository name
Input:
user[models.GitUser]: The user to get the status for
Return:
list of dicts containing repository information
"""
pr_q = models.PullRequest.objects.filter(closed=False, username=username).order_by("number")
if last_modified:
pr_q = pr_q.filter(last_modified__gte=last_modified)
repo_q = repos = models.Repository.objects.filter(pull_requests__username=username, pull_requests__closed=False).distinct()
repos = (repo_q
.order_by("name")
.prefetch_related(Prefetch('pull_requests', queryset=pr_q, to_attr='open_prs'))
.select_related("user__server"))
return get_repos_data(repos)
示例8: all_patients
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def all_patients(request):
"""
Query is written to minimize hits to the database; number of db hits can be
see on the django debug toolbar.
"""
patient_list = mymodels.Patient.objects.all() \
.order_by('last_name') \
.select_related('gender') \
.prefetch_related('case_managers') \
.prefetch_related(Prefetch('workup_set', queryset=workupmodels.Workup.objects.order_by('clinic_day__clinic_date'))) \
.prefetch_related('actionitem_set')
# Don't know how to prefetch history https://stackoverflow.com/questions/45713517/use-prefetch-related-in-django-simple-history
# Source code is https://github.com/treyhunner/django-simple-history/blob/master/simple_history/models.py if we want to try to figure out
return render(request,
'pttrack/all_patients.html',
{'object_list': patient_list})
示例9: prefetch_related
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def prefetch_related(self, *args):
try:
for arg in args:
if isinstance(arg, str):
arg = FastPrefetch.make_from_field(
model=self.model,
field_name=arg
)
elif isinstance(arg, Prefetch):
arg = FastPrefetch.make_from_prefetch(arg, self.model)
if not isinstance(arg, FastPrefetch):
raise Exception("Must be FastPrefetch object")
if arg.field in self.prefetches:
raise Exception(
"Prefetch for field '%s' already exists."
)
self.prefetches[arg.field] = arg
except Exception as e: # noqa
traceback.print_exc()
return self
示例10: _get_django_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def _get_django_queryset(self):
"""Return Django QuerySet with prefetches properly configured."""
prefetches = []
for field, fprefetch in self.prefetches.items():
has_query = hasattr(fprefetch, 'query')
qs = fprefetch.query.queryset if has_query else None
prefetches.append(
Prefetch(field, queryset=qs)
)
queryset = self.queryset
if prefetches:
queryset = queryset.prefetch_related(*prefetches)
return queryset
示例11: get_context_data
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def get_context_data(self, **kwargs):
document = self.object
paragraph_list = document.textunit_set \
.filter(unit_type='paragraph') \
.order_by('id') \
.prefetch_related(
models.Prefetch(
'termusage_set',
queryset=TermUsage.objects.order_by('term__term').select_related('term'),
to_attr='ltu'))
ctx = {'document': document,
'party_list': list(PartyUsage.objects.filter(
text_unit__document=document).values_list('party__name', flat=True)),
'highlight': self.request.GET.get('highlight', ''),
'paragraph_list': paragraph_list}
return ctx
示例12: _ajaxaccounttab_teams
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def _ajaxaccounttab_teams(tab, request, account, more):
context = {}
if account.owner == request.user:
context['is_me'] = True
teams = models.Team.objects.filter(owner_account=account).prefetch_related(Prefetch('members', queryset=models.Member.objects.select_related('ownedcard', 'ownedcard__card').order_by('position'), to_attr='all_members'))
range_aligners = [0,1,2,3,4,3,2,1,0]
for team in teams:
team.owner_account = account
members = [{'position': i, 'virtual': True, 'range_align': range(range_aligners[i])} for i in range(9)]
for member in team.all_members:
member.range_align = members[member.position]['range_align']
members[member.position] = member
team.all_members = members
account.all_teams = teams
context['account'] = account
return context
示例13: _populate_choices
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def _populate_choices(self):
# This is *hackish* but simpler than subclassing ModelChoiceIterator
choices = [("", self.empty_label)]
kwargs = {self.parent_field: None}
queryset = (
self.queryset
.filter(**kwargs)
.prefetch_related(Prefetch(self.related_name, queryset=self.queryset)))
for parent in queryset:
choices.append((self.prepare_value(parent), self.label_from_instance(parent)))
choices.extend(
(self.prepare_value(children), self.label_from_instance(children))
for children in getattr(parent, self.related_name).all())
self.choices = choices
示例14: joins_for_csv_output
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def joins_for_csv_output(self):
return self.select_related('base') \
.prefetch_related(
models.Prefetch(
'base__memberships',
Membership.objects.select_related(
'extra',
'extra__election',
'on_behalf_of__extra',
'post__area',
'post__extra',
).prefetch_related(
'on_behalf_of__identifiers',
'post__area__other_identifiers',
)
),
'base__contact_details',
'base__identifiers',
'base__links',
'images__extra__uploading_user',
)
示例15: setup_eager_loading
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Prefetch [as 别名]
def setup_eager_loading(queryset, request, extra_prefetch=None):
"""Perform necessary eager loading of data."""
# Get the fields to be prefetched
fields = ['bodies', 'venues', 'user_tags', 'offered_achievements']
# Add prefetch for user_ues
if request.user.is_authenticated and hasattr(request.user, 'profile'):
user_query = UserEventStatus.objects.filter(user_id=request.user.profile.id)
fields.append(Prefetch('ues', queryset=user_query, to_attr='uues'))
# Add extra prefetch fields
if extra_prefetch:
fields += extra_prefetch
queryset = queryset.prefetch_related(*fields)
# Prefetch counts
interested_count = Count('followers', distinct=True, filter=Q(ues__status=1))
going_count = Count('followers', distinct=True, filter=Q(ues__status=2))
queryset = queryset.annotate(interested_count=interested_count).annotate(going_count=going_count)
return queryset