本文整理汇总了Python中django.db.models.QuerySet方法的典型用法代码示例。如果您正苦于以下问题:Python models.QuerySet方法的具体用法?Python models.QuerySet怎么用?Python models.QuerySet使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.QuerySet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_for_objects
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def get_for_objects(self, queryset):
"""
Get log entries for the objects in the specified queryset.
:param queryset: The queryset to get the log entries for.
:type queryset: QuerySet
:return: The LogAction objects for the objects in the given queryset.
:rtype: QuerySet
"""
if not isinstance(queryset, QuerySet) or queryset.count() == 0:
return self.none()
content_type = ContentType.objects.get_for_model(queryset.model)
primary_keys = queryset.values_list(queryset.model._meta.pk.name, flat=True)
if isinstance(primary_keys[0], integer_types):
return self.filter(content_type=content_type).filter(Q(object_id__in=primary_keys)).distinct()
else:
return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct()
示例2: _find_subqueries_in_where
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [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
示例3: daily_activity_notifications
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def daily_activity_notifications():
with timer() as t:
for group in Group.objects.all():
with timezone.override(group.timezone):
if timezone.localtime().hour != 20: # only at 8pm local time
continue
for data in fetch_activity_notification_data_for_group(group):
prepare_activity_notification_email(**data).send()
stats.activity_notification_email(
group=data['group'], **{k: v.count()
for k, v in data.items() if isinstance(v, QuerySet)}
)
stats_utils.periodic_task('activities__daily_activity_notifications', seconds=t.elapsed_seconds)
示例4: get_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def get_queryset(self, **kwargs) -> QuerySet:
"""
Get the list of items for this view.
This must be an iterable, and may be a queryset.
Defaults to using `self.queryset`.
This method should always be used rather than accessing `self.queryset`
directly, as `self.queryset` gets evaluated only once, and those results
are cached for all subsequent requests.
You may want to override this if you need to provide different
querysets depending on the incoming request.
(Eg. return a list of items that is specific to the user)
"""
assert self.queryset is not None, (
"'%s' should either include a `queryset` attribute, "
"or override the `get_queryset()` method." % self.__class__.__name__
)
queryset = self.queryset
if isinstance(queryset, QuerySet):
# Ensure queryset is re-evaluated on each request.
queryset = queryset.all()
return queryset
示例5: has_perm
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def has_perm(self, user_obj, perm, obj=None):
if not user_obj.is_anonymous and not user_obj.is_active:
return False
if obj is None:
# Take a shortcut and check KeywordPermissions only if no object are defined.
return KeywordPermissions.has_perm(user_obj, perm)
if isinstance(obj, models.Model):
permission_handler = get_permission_handler(obj)
return permission_handler.has_perm(user_obj, perm, obj=obj)
elif isinstance(obj, models.QuerySet):
permission_handler = get_permission_handler(obj.model)
return permission_handler.has_perm(user_obj, perm, queryset=obj)
elif issubclass(obj, models.Model):
permission_handler = get_permission_handler(obj)
return permission_handler.has_perm(
user_obj, perm, queryset=obj.objects.none()
)
return False
示例6: _get_django_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [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
示例7: __getitem__
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def __getitem__(self, k):
"""Support list index and slicing, similar to Django QuerySet."""
if self._data is not None:
# Query has already been executed. Extract from local cache.
return self._data[k]
# Query hasn't yet been executed. Update queryset.
if isinstance(k, slice):
if k.start is not None:
start = int(k.start)
else:
start = None
if k.stop is not None:
stop = int(k.stop)
else:
stop = None
if k.step:
raise TypeError("Stepping not supported")
self.queryset.query.set_limits(start, stop)
return self.execute()
else:
self.queryset.query.set_limits(k, k+1)
return self.execute()
示例8: get_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def get_queryset(self) -> QuerySet:
"""
Returns a queryset of `carrot.models.MessageLog` objects. If a `search_term` is provided in the request query
params, then the result is filtered based on this. If using postgres, this is done using SearchVectors for
improved performance
"""
search_term = self.request.query_params.get('search', None)
qs = self.queryset.all()
if search_term:
if settings.DATABASES.get('default', {}).get('ENGINE') == 'django.db.backends.postgresql_psycopg2':
qs = qs.annotate(search=SearchVector('task', 'content', 'task_args')).filter(search=search_term)
else:
qs = (
qs.filter(task__icontains=search_term) |
qs.filter(content__icontains=search_term) |
qs.filter(task_args__icontains=search_term)
).distinct()
return qs
示例9: _earliest_or_latest
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def _earliest_or_latest(self, field_name=None, direction="-"):
"""
Overrides QuerySet._earliest_or_latest to add pk for secondary ordering
"""
order_by = field_name or getattr(self.model._meta, "get_latest_by")
assert bool(order_by), (
"earliest() and latest() require either a "
"field_name parameter or 'get_latest_by' in the model"
)
assert (
self.query.can_filter()
), "Cannot change a query once a slice has been taken."
obj = self._clone()
obj.query.set_limits(high=1)
obj.query.clear_ordering(force_empty=True)
# add pk as secondary ordering for Submissions
obj.query.add_ordering(
"%s%s" % (direction, order_by), "%s%s" % (direction, "pk")
)
return obj.get()
示例10: drop_clusters
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def drop_clusters(self, exclude_task_ids: Set = None, exclude_project_clustering_id: int = None):
project = self
# Stop running tusks
from apps.task.tasks import purge_task
from apps.project.tasks import ClusterProjectDocuments
task_qr = project.project_tasks \
.filter(name=ClusterProjectDocuments.name, status__in=UNREADY_STATES) # type: QuerySet
if exclude_task_ids:
task_qr = task_qr.exclude(pk__in=exclude_task_ids)
for task in task_qr:
purge_task(task.pk, wait=True, timeout=1.5)
# delete DocumentClusters
for pcl in project.projectclustering_set.all():
pcl.document_clusters.all().delete()
# delete ProjectClustering
project.projectclustering_set.exclude(id=exclude_project_clustering_id).delete()
# delete ClusterProjectDocuments Tasks
to_delete_qr = project.project_tasks.filter(name=ClusterProjectDocuments.name,
status__in=[SUCCESS, PENDING]) # type: QuerySet
if exclude_task_ids:
to_delete_qr = to_delete_qr.exclude(pk__in=exclude_task_ids)
to_delete_qr.delete()
示例11: __init__
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def __init__(self,
queryset: Optional[Union[QuerySet, List[Document]]] = None,
project_id: Optional[int] = None,
project_name_filter: Optional[str] = None,
unit_type: str = 'sentence',
feature_source: str = 'term',
drop_empty_rows=True,
drop_empty_columns=True,
external_feature_names=None,
log_message: Callable[[str, str], None] = None):
super().__init__(queryset, project_id, project_name_filter,
unit_type, feature_source,
drop_empty_rows, drop_empty_columns,
external_feature_names, log_message)
self.transformer = None # type: Optional[BaseTransformer]
self.project_ids = [] # type: List[str]
示例12: test_shouldInjectTheField
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def test_shouldInjectTheField(self): # pylint: disable=no-self-use
assert_that(BasicTestModel, has_property('river', is_(instance_of(RiverObject))))
assert_that(BasicTestModel.river, has_property('my_field', is_(instance_of(ClassWorkflowObject))))
content_type = ContentType.objects.get_for_model(BasicTestModel)
state1 = StateObjectFactory.create(label="state1")
state2 = StateObjectFactory.create(label="state2")
workflow = WorkflowFactory(content_type=content_type, field_name="my_field", initial_state=state1)
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0
)
test_model = BasicTestModel.objects.create()
assert_that(test_model, has_property('river', is_(instance_of(RiverObject))))
assert_that(test_model.river, has_property('my_field', is_(instance_of(InstanceWorkflowObject))))
assert_that(BasicTestModel.river.my_field, has_property('initial_state', is_(instance_of(State))))
assert_that(BasicTestModel.river.my_field, has_property('final_states', is_(instance_of(QuerySet))))
assert_that(test_model.river.my_field, has_property('approve', has_property("__call__")))
assert_that(test_model.river.my_field, has_property('on_initial_state', is_(instance_of(bool))))
assert_that(test_model.river.my_field, has_property('on_final_state', is_(instance_of(bool))))
示例13: confirmed
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def confirmed(self) -> QuerySet[QueuedSong]:
"""Returns a QuerySet containing all confirmed songs.
Confirmed songs are not in the process of being made available."""
return self.exclude(internal_url="")
示例14: files
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def files(self) -> models.QuerySet:
"""Get referenced path objects in default storage location."""
return self.default_storage_location.files
示例15: get_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import QuerySet [as 别名]
def get_queryset(self) -> models.QuerySet:
"""Override default queryset."""
return super().get_queryset().filter(status="OK")