本文整理匯總了Python中django.db.models.Q屬性的典型用法代碼示例。如果您正苦於以下問題:Python models.Q屬性的具體用法?Python models.Q怎麽用?Python models.Q使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類django.db.models
的用法示例。
在下文中一共展示了models.Q屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: choose_product
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def choose_product(request, order_id, product_id=None, target_url="orders-add_product"):
"""
order_id can be either Service Order or Purchase Order
"""
data = {'order': order_id}
data['action'] = request.path
data['target_url'] = target_url
if request.method == "POST":
query = request.POST.get('q')
if len(query) > 2:
products = Product.objects.filter(
Q(code__icontains=query) | Q(title__icontains=query)
)
data['products'] = products
return render(request, 'products/choose-list.html', data)
return render(request, 'products/choose.html', data)
示例2: choose_customer
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def choose_customer(request, pk):
"""
Lets the user search for a customer for this order
"""
if request.method == "POST":
customers = Customer.objects.none()
kind = request.POST.get('kind')
query = request.POST.get('name')
if len(query) > 2:
customers = Customer.objects.filter(
Q(fullname__icontains=query) | Q(email__icontains=query) | Q(phone__contains=query)
)
if kind == 'companies':
customers = customers.filter(is_company=True)
if kind == 'contacts':
customers = customers.filter(is_company=False)
data = {'customers': customers, 'order_id': pk}
return render(request, "customers/choose-list.html", data)
data = {'action': request.path}
return render(request, 'customers/choose.html', data)
示例3: products
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def products(request):
"""
Searches our local inventory
"""
query = request.GET.get("q")
request.session['search_query'] = query
results = Product.objects.filter(
Q(code__icontains=query) | Q(title__icontains=query) | Q(eee_code__icontains=query)
)
page = request.GET.get("page")
products = paginate(results, page, 50)
title = _(u'Search results for "%s"') % query
group = ProductCategory(title=_('All'), slug='all')
return render(request, 'products/search.html', locals())
示例4: devices
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def devices(request):
"""
Searching for devices from the main navbar
"""
query = request.GET.get("q", '').strip()
request.session['search_query'] = query
query = query.upper()
valid_arg = gsxws.validate(query)
if valid_arg in ('serialNumber', 'alternateDeviceId',):
return redirect(search_gsx, "warranty", valid_arg, query)
devices = Device.objects.filter(
Q(sn__icontains=query) | Q(description__icontains=query)
)
title = _(u'Devices matching "%s"') % query
return render(request, "devices/search.html", locals())
示例5: _authorized_approvals
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def _authorized_approvals(self, as_user):
group_q = Q()
for g in as_user.groups.all():
group_q = group_q | Q(groups__in=[g])
permissions = []
for backend in auth.get_backends():
permissions.extend(backend.get_all_permissions(as_user))
permission_q = Q()
for p in permissions:
label, codename = p.split('.')
permission_q = permission_q | Q(permissions__content_type__app_label=label,
permissions__codename=codename)
return TransitionApproval.objects.filter(
Q(workflow=self.workflow, status=PENDING) &
(
(Q(transactioner__isnull=True) | Q(transactioner=as_user)) &
(Q(permissions__isnull=True) | permission_q) &
(Q(groups__isnull=True) | group_q)
)
)
示例6: profile_handler
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def profile_handler(request):
""" HTTP request handler for profile request """
profiles = ET.Element('profiles')
if request.user.is_authenticated():
uid = request.user.id
logging.debug("User Authenticated (%s)" % request.user.username)
entries = DeviceProfile.objects.filter(Q(user=uid) | Q(shared=True))
for e in entries:
profile = _build_device_profile(e)
profiles.append(profile)
entries = Collection.objects.all()
for e in entries:
profile = _build_collection_profile(e)
profiles.append(profile)
return HttpResponse(Response.success('profile', 'ok', xml=profiles))
示例7: get_queryset
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def get_queryset(self):
queryset = self.queryset
if self.request.GET.get("status") == "enabled":
queryset = queryset.only_enabled()
elif self.request.GET.get("status") == "disabled":
queryset = queryset.only_disabled()
if "text" in self.request.GET:
text = self.request.GET.get("text")
if "\x00" in text:
raise ParseError("Null bytes in text")
queryset = queryset.filter(
Q(latest_revision__name__contains=text)
| Q(latest_revision__extra_filter_expression__contains=text)
)
return queryset
示例8: get_queryset
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def get_queryset(self):
queryset = self.queryset
if self.request.GET.get("status") == "enabled":
queryset = queryset.only_enabled()
elif self.request.GET.get("status") == "disabled":
queryset = queryset.only_disabled()
if "text" in self.request.GET:
text = self.request.GET.get("text")
if "\x00" in text:
raise ParseError("Null bytes in text")
tokens = set(re.split(r"[ /_-]", text))
query = Q()
for token in tokens:
query &= (
Q(latest_revision__name__icontains=token)
| Q(latest_revision__extra_filter_expression__icontains=token)
| Q(latest_revision__arguments_json__icontains=token)
)
queryset = queryset.filter(query)
return queryset
示例9: fix_prev_and_next_run
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def fix_prev_and_next_run(instance, using):
prev_run = instance.order and (
SpeedRun.objects.filter(event=instance.event_id, order__lt=instance.order)
.using(using)
.order_by('order')
.last()
)
next_run = instance.order and (
SpeedRun.objects.filter(event=instance.event_id, order__gt=instance.order)
.using(using)
.order_by('order')
.first()
)
prizes = Prize.objects.using(using).filter(
Q(prev_run=instance)
| Q(next_run=instance)
| Q(startrun=instance)
| Q(endrun=instance)
)
if prev_run:
prizes = prizes | Prize.objects.using(using).filter(
Q(startrun=next_run) | Q(endrun=prev_run)
)
for prize in prizes:
prize.save(using=using)
示例10: clean
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def clean(self):
sameBid = BidSuggestion.objects.filter(
Q(name__iexact=self.name)
& (
Q(bid__event=self.bid.get_event())
| Q(bid__speedrun__event=self.bid.get_event())
)
)
if sameBid.exists():
if sameBid.count() > 1 or sameBid[0].id != self.id:
raise ValidationError(
'Cannot have a bid suggestion with the same name within the same event.'
)
# If set, limit the length of suggestions based on the parent bid's
# setting
示例11: donation_feed_filter
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def donation_feed_filter(feed_name, noslice, params, query, user):
if (
feed_name not in ['recent', 'toprocess', 'toread', 'all']
and feed_name is not None
):
raise ValueError(f'Unknown feed name `{feed_name}`')
if feed_name == 'recent':
query = get_recent_donations(
**feed_params(noslice, params, {'donations': query})
)
elif feed_name == 'toprocess':
if not user.has_perm('tracker.view_comments'):
raise PermissionDenied
query = query.filter((Q(commentstate='PENDING') | Q(readstate='PENDING')))
elif feed_name == 'toread':
query = query.filter(Q(readstate='READY'))
if feed_name != 'all':
query = query.filter(transactionstate='COMPLETED', testdonation=False)
elif not user.has_perm('tracker.view_pending'):
raise PermissionDenied
return query
示例12: prize_feed_filter
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def prize_feed_filter(feed_name, noslice, params, query, user):
if feed_name == 'current':
call_params = {}
if 'time' in params:
call_params['query_offset'] = default_time(params['time'])
query = query.filter(current_prizes_filter(**call_params))
elif feed_name == 'future':
query = query.filter(upcoming_prizes_filter(**feed_params(noslice, params)))
elif feed_name == 'won':
# TODO: are these used? doesn't seem to take multi-prizes into account
query = query.filter(Q(prizewinner__isnull=False))
elif feed_name == 'unwon':
query = query.filter(Q(prizewinner__isnull=True))
elif feed_name == 'todraw':
query = query.filter(todraw_prizes_filter())
if feed_name != 'all':
query = query.filter(state='ACCEPTED')
elif not user.has_perm('tracker.change_prize'):
raise PermissionDenied
return query
示例13: model_specific_filter
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def model_specific_filter(model, params, user):
query = Q()
model = normalize_model_param(model)
specifics = _SpecificFields[model]
keys = list(params.keys())
filters = {k: single(params, k) for k in keys if k in specifics}
if params: # anything leftover is unrecognized
raise KeyError("Invalid search parameters: '%s'" % ','.join(params.keys()))
for param, value in filters.items():
check_field_permissions(model, param, value, user)
specific = specifics[param]
field_query = Q()
if isinstance(specific, str) or not hasattr(specific, '__iter__'):
specific = [specific]
for search_key in specific:
field_query |= Q(**{search_key: value})
query &= field_query
return query
示例14: user_readable
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def user_readable(self, user):
"""Queryset for boards that the user has read permissions for."""
base = super(BoardModelManager, self).get_queryset()
if user.is_staff:
return base
if not user.is_authenticated:
return base.filter(permissions__read_board=AuthLevels.anyone.key)
else:
public = Q(permissions__read_board=AuthLevels.anyone.key)
registered = Q(permissions__read_board=AuthLevels.registered.key)
created = Q(permissions__board__creator=user)
collab = (
Q(permissions__read_board=AuthLevels.collaborators.key) &
Q(permissions__collaborators=user)
)
return base.filter(public | registered | created | collab)
示例15: _get_matching_hpo_terms
# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Q [as 別名]
def _get_matching_hpo_terms(query, projects):
"""Returns OMIM records that match the given query string"""
records = HumanPhenotypeOntology.objects.filter(
Q(hpo_id__icontains=query) | Q(name__icontains=query)
).annotate(
name_start=ExpressionWrapper(Q(name__istartswith=query), output_field=BooleanField()),
hpo_id_start=ExpressionWrapper(Q(hpo_id__istartswith=query), output_field=BooleanField()),
).only('hpo_id', 'name', 'category_id').order_by(
'-name_start', '-hpo_id_start', 'name').distinct()[:MAX_RESULTS_PER_CATEGORY]
result = []
for record in records:
result.append({
'key': record.hpo_id,
'title': record.name,
'description': '({})'.format(record.hpo_id),
'category': record.category_id,
})
return result