當前位置: 首頁>>代碼示例>>Python>>正文


Python models.Q屬性代碼示例

本文整理匯總了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) 
開發者ID:fpsw,項目名稱:Servo,代碼行數:22,代碼來源:product.py

示例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) 
開發者ID:fpsw,項目名稱:Servo,代碼行數:27,代碼來源:order.py

示例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()) 
開發者ID:fpsw,項目名稱:Servo,代碼行數:20,代碼來源:search.py

示例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()) 
開發者ID:fpsw,項目名稱:Servo,代碼行數:22,代碼來源:search.py

示例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)
            )
        ) 
開發者ID:javrasya,項目名稱:django-river,代碼行數:25,代碼來源:orm_driver.py

示例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)) 
開發者ID:CiscoDevNet,項目名稱:yang-explorer,代碼行數:19,代碼來源:profile_view.py

示例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 
開發者ID:mozilla,項目名稱:normandy,代碼行數:20,代碼來源:views.py

示例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 
開發者ID:mozilla,項目名稱:normandy,代碼行數:26,代碼來源:views.py

示例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) 
開發者ID:GamesDoneQuick,項目名稱:donation-tracker,代碼行數:27,代碼來源:prize.py

示例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 
開發者ID:GamesDoneQuick,項目名稱:donation-tracker,代碼行數:18,代碼來源:bid.py

示例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 
開發者ID:GamesDoneQuick,項目名稱:donation-tracker,代碼行數:23,代碼來源:search_feeds.py

示例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 
開發者ID:GamesDoneQuick,項目名稱:donation-tracker,代碼行數:22,代碼來源:search_feeds.py

示例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 
開發者ID:GamesDoneQuick,項目名稱:donation-tracker,代碼行數:20,代碼來源:search_filters.py

示例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) 
開發者ID:twschiller,項目名稱:open-synthesis,代碼行數:18,代碼來源:models.py

示例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 
開發者ID:macarthur-lab,項目名稱:seqr,代碼行數:21,代碼來源:awesomebar_api.py


注:本文中的django.db.models.Q屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。