本文整理汇总了Python中django.db.models.query_utils.Q属性的典型用法代码示例。如果您正苦于以下问题:Python query_utils.Q属性的具体用法?Python query_utils.Q怎么用?Python query_utils.Q使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类django.db.models.query_utils
的用法示例。
在下文中一共展示了query_utils.Q属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def handle(self, *args, **options):
source_project_name = options['source']
target_project_name = options['target']
source_project = Project.objects.get(Q(name=source_project_name) | Q(guid=source_project_name))
target_project = Project.objects.get(Q(name=target_project_name) | Q(guid=target_project_name))
tags = VariantTagType.objects.filter(project=source_project)
for tag in tags:
tag.pk = None
tag.id = None
tag.project = target_project
tag.save()
logger.info('Saved tag %s (new id = %d)' % (tag.name, tag.id))
示例2: test_normal_command
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def test_normal_command(self):
out = StringIO()
call_command('add_project_tag', '--project={}'.format(TAG_ARGUMENTS["project"]),
'--name={}'.format(TAG_ARGUMENTS["name"]), '--order={}'.format(TAG_ARGUMENTS["order"]),
'--category={}'.format(TAG_ARGUMENTS["category"]),
'--description={}'.format(TAG_ARGUMENTS["description"]),
'--color={}'.format(TAG_ARGUMENTS["color"]), stdout = out)
self.assertEqual('', out.getvalue())
project = Project.objects.get(Q(name = TAG_ARGUMENTS["project"]))
variantTagType = VariantTagType.objects.get(name=TAG_ARGUMENTS["name"], project=project)
tag_info = {
"project": variantTagType.project.name,
"name": variantTagType.name,
"order": variantTagType.order,
"category": variantTagType.category,
"description": variantTagType.description,
"color": variantTagType.color
}
self.assertDictEqual(tag_info, TAG_ARGUMENTS)
示例3: as_sql
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def as_sql(self, compiler, connection, **extra_context):
if self.filter:
if connection.features.supports_aggregate_filter_clause:
filter_sql, filter_params = self.filter.as_sql(compiler, connection)
template = self.filter_template % extra_context.get('template', self.template)
sql, params = super().as_sql(compiler, connection, template=template, filter=filter_sql)
return sql, params + filter_params
else:
copy = self.copy()
copy.filter = None
condition = When(Q())
source_expressions = copy.get_source_expressions()
condition.set_source_expressions([self.filter, source_expressions[0]])
copy.set_source_expressions([Case(condition)] + source_expressions[1:])
return super(Aggregate, copy).as_sql(compiler, connection, **extra_context)
return super().as_sql(compiler, connection, **extra_context)
示例4: delete_batch
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def delete_batch(self, pk_list, using):
"""
Set up and execute delete queries for all the objects in pk_list.
More than one physical query may be executed if there are a
lot of values in pk_list.
"""
# number of objects deleted
num_deleted = 0
field = self.get_meta().pk
for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
self.where = self.where_class()
self.add_q(Q(
**{field.attname + '__in': pk_list[offset:offset + GET_ITERATOR_CHUNK_SIZE]}))
num_deleted += self.do_query(self.get_meta().db_table, self.where, using=using)
return num_deleted
示例5: complex_filter
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def complex_filter(self, filter_obj):
"""
Return a new QuerySet instance with filter_obj added to the filters.
filter_obj can be a Q object or a dictionary of keyword lookup
arguments.
This exists to support framework features such as 'limit_choices_to',
and usually it will be more natural to use other methods.
"""
if isinstance(filter_obj, Q):
clone = self._chain()
clone.query.add_q(filter_obj)
return clone
else:
return self._filter_or_exclude(None, **filter_obj)
示例6: active
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def active(self):
""" Returns CourseRuns that have not yet ended and meet the following enrollment criteria:
- Open for enrollment
- OR will be open for enrollment in the future
- OR have no specified enrollment close date (e.g. self-paced courses)
Returns:
QuerySet
"""
now = datetime.datetime.now(pytz.UTC)
return self.filter(
(
Q(end__gt=now) |
Q(end__isnull=True)
) & (
Q(enrollment_end__gt=now) |
Q(enrollment_end__isnull=True)
)
)
示例7: enrollable
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def enrollable(self):
""" Returns course runs that are currently open for enrollment.
A course run is considered open for enrollment if its enrollment start date
has passed, is now or is None, AND its enrollment end date is in the future or is None.
Returns:
QuerySet
"""
now = datetime.datetime.now(pytz.UTC)
return self.filter(
(
Q(enrollment_end__gt=now) |
Q(enrollment_end__isnull=True)
) & (
Q(enrollment_start__lte=now) |
Q(enrollment_start__isnull=True)
)
)
示例8: delete_batch
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def delete_batch(self, pk_list, using, field=None):
"""
Set up and execute delete queries for all the objects in pk_list.
More than one physical query may be executed if there are a
lot of values in pk_list.
"""
# number of objects deleted
num_deleted = 0
if not field:
field = self.get_meta().pk
for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
self.where = self.where_class()
self.add_q(Q(
**{field.attname + '__in': pk_list[offset:offset + GET_ITERATOR_CHUNK_SIZE]}))
num_deleted += self.do_query(self.get_meta().db_table, self.where, using=using)
return num_deleted
示例9: edit_category
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def edit_category(request, category_id):
if request.user.perms.access_level > 2:
return render(request, 'unauthorized.html')
page_title = 'Editing category'
box_title = page_title
category = get_object_or_404(Category, pk=category_id)
if request.method == 'POST':
form = categories.CategoryForm(request.POST)
if form.is_valid():
category_type = form.cleaned_data['categoryType']
if Category.objects.filter(~Q(pk=category_id), categoryType__iexact=category_type).count() > 0:
errors = ['Category with name \"%s\" already exists.' % category_type]
else:
query = dict(categoryType=category_type)
Category.objects.filter(pk=category_id).update(**query)
success_msg = 'Category Updated.'
return redirect('/categories/')
else:
form = categories.CategoryForm(instance=category)
return render(request, 'generic_form.html', locals())
示例10: view_all_pluginservers
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def view_all_pluginservers(request):
render_vars = dict()
if request.user.perms.access_level > 3:
return render(request, 'unauthorized.html')
search_form = pluginserver.PluginSearchForm()
if request.method == "POST":
search_form = pluginserver.PluginSearchForm(request.POST)
if search_form.is_valid():
search_term = search_form.cleaned_data.get('search_term')
render_vars['plugins'] = Plugin.objects.filter(Q(name__icontains=search_term) |
Q(description__icontains=search_term))
render_vars['search_term'] = search_term
if request.method == "GET":
try:
render_vars['servers'] = PluginServer.objects.all()
except PluginServer.DoesNotExist:
render_vars['servers'] = None
render_vars[search_form] = search_form
return render(request, 'view_all_pluginservers.html', render_vars)
示例11: edit_pluginserver
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def edit_pluginserver(request, pluginserver_id):
if request.user.perms.access_level > 2:
return render(request, 'unauthorized.html')
page_title = 'Editing plugin server'
box_title = page_title
ps = get_object_or_404(PluginServer, pk=pluginserver_id)
if request.method == "POST":
form = pluginserver.PluginServerForm(request.POST)
if form.is_valid():
name = form.cleaned_data.get('name')
url = form.cleaned_data.get('url')
status = form.cleaned_data.get('status')
ssl_verify = form.cleaned_data.get('ssl_verify')
if PluginServer.objects.filter(~Q(pk=pluginserver_id), url__iexact=url).count() > 0:
errors = ['A server with URL: %s already exists' % url]
else:
query = dict(name=name, url=url, status=status, ssl_verify=ssl_verify)
PluginServer.objects.filter(pk=pluginserver_id).update(**query)
return redirect('/pluginservers/view/%s/' % pluginserver_id)
else:
form = pluginserver.PluginServerForm(instance=ps)
return render(request, 'generic_form.html', locals())
示例12: edit_team
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def edit_team(request, team_id):
if request.user.perms.access_level > 2:
return render(request, 'unauthorized.html')
page_title = 'Editing team'
box_title = page_title
team = get_object_or_404(Team, pk=team_id)
if request.method == 'POST':
form = teams.TeamForm(request.POST)
if form.is_valid():
team_name = form.cleaned_data.get('name')
if Team.objects.filter(~Q(pk=team_id), name__iexact=team_name).count() > 0:
errors = ['Team with name \"%s\" already exists.' % team_name]
else:
team.name = team_name
team.description = form.cleaned_data.get('description')
team.members = form.cleaned_data.get('members')
team.save()
return redirect('/teams/')
else:
form = teams.TeamForm(instance=team)
return render(request, 'generic_form.html', locals())
示例13: get_current_m2m_diff
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def get_current_m2m_diff(self, instance, new_objects):
"""
:param instance: Versionable object
:param new_objects: objects which are about to be associated with
instance
:return: (being_removed id list, being_added id list)
:rtype : tuple
"""
new_ids = self.pks_from_objects(new_objects)
relation_manager = self.__get__(instance)
filter = Q(**{relation_manager.source_field.attname: instance.pk})
qs = self.through.objects.current.filter(filter)
try:
# Django 1.7
target_name = relation_manager.target_field.attname
except AttributeError:
# Django 1.6
target_name = relation_manager.through._meta.get_field_by_name(
relation_manager.target_field_name)[0].attname
current_ids = set(qs.values_list(target_name, flat=True))
being_removed = current_ids - new_ids
being_added = new_ids - current_ids
return list(being_removed), list(being_added)
示例14: _get_archives_to_start
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def _get_archives_to_start(self, now):
"""
If the archiver is killed unexpectedly, we need to account for the
special case of its "first pass", where we need to re-start should-be
ongoing archivals. We also call ._handle_restarts() here to capture
the special case where the stream was killed for whatever reason.
"""
r = Archive.objects\
.filter(started__lte=now)\
.exclude(pk__in=[a.pk for a in self.tracking])
if self.first_pass_completed:
r = r.exclude(is_running=False)
self.first_pass_completed = True
return self._handle_restarts(
r.filter(Q(stopped__gt=now) | Q(stopped__isnull=True))
).exclude(
user__status=User.STATUS_DISABLED
)
示例15: test_partial_index
# 需要导入模块: from django.db.models import query_utils [as 别名]
# 或者: from django.db.models.query_utils import Q [as 别名]
def test_partial_index(self):
with connection.schema_editor() as editor:
index = Index(
name='recent_article_idx',
fields=['pub_date'],
condition=Q(
pub_date__gt=datetime.datetime(
year=2015, month=1, day=1,
# PostgreSQL would otherwise complain about the lookup
# being converted to a mutable function (by removing
# the timezone in the cast) which is forbidden.
tzinfo=timezone.get_current_timezone(),
),
)
)
self.assertIn(
'WHERE %s.%s' % (editor.quote_name(Article._meta.db_table), editor.quote_name("pub_date")),
str(index.create_sql(Article, schema_editor=editor))
)
editor.add_index(index=index, model=Article)
self.assertIn(index.name, connection.introspection.get_constraints(
cursor=connection.cursor(), table_name=Article._meta.db_table,
))
editor.remove_index(index=index, model=Article)