How to use the django.db.models.Q function in Django

To help you get started, we’ve selected a few Django examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github django / django / tests / or_lookups / tests.py View on Github external
def test_q_repr(self):
        or_expr = Q(baz=Article(headline="Foö"))
        self.assertEqual(repr(or_expr), "))>")
        negated_or = ~Q(baz=Article(headline="Foö"))
        self.assertEqual(repr(negated_or), ")))>")
github BRCAChallenge / brca-exchange / website / django / users / views.py View on Github external
def user_locations(request):
    search = request.GET.get('search', '')
    roles = request.GET.getlist('roles[]')
    query = MyUser.objects.filter(is_approved=True)
    if roles:
        query = query.filter(role__in=roles)

    search_query = Q()
    for term in search.split():
        search_query &= ( Q(firstName__icontains=term) | Q(lastName__icontains=term)
                        | Q(institution__icontains=term) | Q(role_other__icontains=term)
                        | Q(city__icontains=term) | Q(state__icontains=term) | Q(country__icontains=term)
                        )
    query = query.filter(search_query)

    fields = ['id', 'firstName', 'lastName', 'title', 'role', 'role_other', 'institution', 'city', 'state', 'country', 'latitude', 'longitude', 'has_image']
    response = JsonResponse({'data': list(query.values(*fields))})
    response['Access-Control-Allow-Origin'] = '*'
    return response
github openplans / openblock / ebpub / ebpub / neighbornews / views.py View on Github external
item.attributes[key] = form.cleaned_data[key]

        # 'categories'
        cats = [cat.strip() for cat in form.cleaned_data['categories'].split(',') if cat.strip()]
        if len(cats):
            lookups = set()
            for cat in cats:
                code = _category_code(cat)
                nice_name = _category_nice_name(cat)
                try:
                    # We don't call get_or_create() yet because we
                    # only want to look up by the normalized code, to
                    # avoid dupes with slightly different names.
                    from django.db.models import Q
                    lu = Lookup.objects.filter(
                        Q(schema_field=cat_field),
                        Q(code=code) | Q(name=nice_name)
                        )[0]
                except (IndexError, Lookup.DoesNotExist):
                    # We know it doesn't exist, but use get_or_create_lookup()
                    # here b/c that takes care of the slug.
                    lu = Lookup.objects.get_or_create_lookup(cat_field, nice_name, code=code)
                lookups.add(lu.id)
            item.attributes['categories'] = ','.join(['%d' % luid for luid in lookups])

        detail_url = reverse('ebpub-newsitem-detail',
                             args=(schema.slug, '%d' % item.id))
        if action == 'create':
            messages.add_message(request, messages.INFO, '%s created.' % schema.name)
        else:
            messages.add_message(request, messages.INFO, '%s edited.' % schema.name)
        return HttpResponseRedirect(detail_url)
github F0RE1GNERS / eoj3 / blog / models.py View on Github external
def get_status_list(self, show_all=False, filter_user=None):
    q = models.Q()
    if not show_all:
      q &= models.Q(is_reward=True, contest=None)
      if filter_user:
        q |= models.Q(contest__participants__username__contains=filter_user.username)
        q |= models.Q(contest__managers__username__contains=filter_user.username)
        q |= models.Q(contest__volunteers__username__contains=filter_user.username)
        q |= models.Q(contest__authors__username__contains=filter_user.username)
    else:
      q &= models.Q(is_reward=True)
    return self.filter(q).distinct()
github zulip / zulip / zerver / lib / actions.py View on Github external
raise JsonableError("User not authorized for this query")

    # Listing public streams are disabled for the mit.edu realm.
    include_public = include_public and user_profile.realm.domain != "mit.edu"
    # Start out with all streams in the realm with subscribers
    query = get_occupied_streams(user_profile.realm)

    if not include_all_active:
        user_subs = Subscription.objects.select_related("recipient").filter(
            active=True, user_profile=user_profile,
            recipient__type=Recipient.STREAM)

        if include_subscribed:
            recipient_check = Q(id__in=[sub.recipient.type_id for sub in user_subs])
        if include_public:
            invite_only_check = Q(invite_only=False)

        if include_subscribed and include_public:
            query = query.filter(recipient_check | invite_only_check)
        elif include_public:
            query = query.filter(invite_only_check)
        elif include_subscribed:
            query = query.filter(recipient_check)
        else:
            # We're including nothing, so don't bother hitting the DB.
            query = []

    def make_dict(row):
        return dict(
            stream_id = row.id,
            name = row.name,
            description = row.description,
github yunity / karrot-frontend / foodsaving / invitations / models.py View on Github external
def expired_q(self):
        return Q(expires_at__lt=timezone.now())
github devilry / devilry-django / devilry / devilry_admin / views / subject / createperiod.py View on Github external
def get_initial(self):
        initial = super(CreateView, self).get_initial()
        if self.previous_period:
            namesuggestion = nodenamesuggestor.Suggest(long_name=self.previous_period.long_name,
                                                       short_name=self.previous_period.short_name)
            if namesuggestion.has_suggestion():
                namecollision_queryset = self.subject.periods.filter(
                    models.Q(long_name=namesuggestion.suggested_long_name) |
                    models.Q(short_name=namesuggestion.suggested_short_name))
                if not namecollision_queryset.exists():
                    initial['long_name'] = namesuggestion.suggested_long_name
                    initial['short_name'] = namesuggestion.suggested_short_name
        return initial
github cloudera / hue / apps / oozie / src / oozie / views / editor.py View on Github external
def list_workflows(request):
  show_setup_app = True
  data = Workflow.objects

  if not SHARE_JOBS.get() and not request.user.is_superuser:
    data = data.filter(owner=request.user)
  else:
    data = data.filter(Q(is_shared=True) | Q(owner=request.user))

  data = data.order_by('-last_modified')

  return render('editor/list_workflows.mako', request, {
    'jobs': list(data),
    'currentuser': request.user,
    'show_setup_app': show_setup_app,
  })
github django-lfs / lfs / manage / views / product / accessories.py View on Github external
s["accessories_page"] = page
    s["filter"] = filter_
    s["accessories_category_filter"] = category_filter

    try:
        s["accessories-amount"] = int(r.get("accessories-amount", 
                                      s.get("accessories-amount")))
    except TypeError:
        s["accessories-amount"] = 10
    
    filters = Q()
    if filter_:
        filters &= Q(name__icontains = filter_)
        filters |= Q(sku__icontains = filter_)
        filters |= (Q(sub_type = VARIANT) & Q(active_sku = False) & Q(parent__sku__icontains = filter_))
        filters |= (Q(sub_type = VARIANT) & Q(active_name = False) & Q(parent__name__icontains = filter_))
        
    if category_filter:
        if category_filter == "None":
            filters &= Q(categories=None)
        else:
            # First we collect all sub categories and using the `in` operator
            category = lfs_get_object_or_404(Category, pk=category_filter)
            categories = [category]
            categories.extend(category.get_all_children())

            filters &= Q(categories__in = categories)

    products = Product.objects.filter(filters).exclude(pk=product_id)
    
    paginator = Paginator(products.exclude(pk__in = accessory_ids), s["accessories-amount"])
github kirstykitto / CLAtoolkit / clatoolkit_project / dataintegration / core / di_utils.py View on Github external
elif platform == "facebook":
        userprofile = UserProfile.objects.filter(fb_id__iexact=sm_id)
    elif platform == "forum":
        userprofile = UserProfile.objects.filter(forum_id__iexact=sm_id)
    elif platform == "youtube":
            userprofile = UserProfile.objects.filter(google_account_name__iexact=sm_id)
    elif platform == "github":
        userprofile = UserProfile.objects.filter(github_account_name__iexact=sm_id)
    elif platform == 'trello':
        userprofile = UserProfile.objects.filter(trello_account_name__iexact=sm_id)
    elif platform.lower() == 'blog':
        userprofile = UserProfile.objects.filter(blog_id__iexact=sm_id)

    else:
        #platform must be = all
        userprofile = UserProfile.objects.filter(Q(twitter_id__iexact=sm_id) | Q(fb_id__iexact=sm_id) | Q(forum_id__iexact=sm_id) | Q(google_account_name__iexact=sm_id))
    if len(userprofile)>0:
        username = userprofile[0].user.username
    else:
        username = sm_id # user may not be registered but display platform username
    return username