当前位置: 首页>>代码示例>>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;未经允许,请勿转载。