Questions tagged [django-q]

A Q() object encapsulates a SQL expression in a Python object that can be used in database-related operations.

In general, Q() objects make it possible to define and reuse conditions. This permits the construction of complex database queries using | (OR) and & (AND) operators; in particular, it is not otherwise possible to use OR in QuerySets.

Complex lookups with Q objects

Keyword argument queries – in filter(), etc. – are “AND”ed together. If you need to execute more complex queries (for example, queries with OR statements), you can use Q objects.

A Q object (django.db.models.Q) is an object used to encapsulate a collection of keyword arguments. These keyword arguments are specified as in “Field lookups” above.

For example, this Q object encapsulates a single LIKE query:

from django.db.models import Q
Q(question__startswith='What')

Q objects can be combined using the & and | operators. When an operator is used on two Q objects, it yields a new Q object.

For example, this statement yields a single Q object that represents the “OR” of two "question__startswith" queries:

Q(question__startswith='Who') | Q(question__startswith='What')

This is equivalent to the following SQL WHERE clause:

WHERE question LIKE 'Who%' OR question LIKE 'What%'

You can compose statements of arbitrary complexity by combining Q objects with the & and | operators and use parenthetical grouping. Also, Q objects can be negated using the ~ operator, allowing for combined lookups that combine both a normal query and a negated (NOT) query:

Q(question__startswith='Who') | ~Q(pub_date__year=2005)

Each lookup function that takes keyword-arguments (e.g. filter(), exclude(), get()) can also be passed one or more Q objects as positional (not-named) arguments. If you provide multiple Q object arguments to a lookup function, the arguments will be “AND”ed together. For example:

Poll.objects.get(
    Q(question__startswith='Who'),
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)

... roughly translates into the SQL:

SELECT * from polls WHERE question LIKE 'Who%'
    AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')

Lookup functions can mix the use of Q objects and keyword arguments. All arguments provided to a lookup function (be they keyword arguments or Q objects) are “AND”ed together. However, if a Q object is provided, it must precede the definition of any keyword arguments. For example:

Poll.objects.get(
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
    question__startswith='Who')

... would be a valid query, equivalent to the previous example; but:

# INVALID QUERY
Poll.objects.get(
    question__startswith='Who',
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))

... would not be valid.

Links

249 questions
3
votes
1 answer

Django search for strings containing spaces

I have a seach by name function, which should return the name of one person, if the search matches the first name or the last name. The problem is that if i search for strings like 'firstname lastname' it doesn't find the name that matches (guess…
dana
  • 5,168
  • 20
  • 75
  • 116
3
votes
0 answers

Getting the query from a django Q() object

I have a Django queryset where I have to use the .extra(select=) method, since I'm calculating a field that requires a WHERE statement subfilter. I use this WHERE clause in a number of places, and I'd like to be obeying DRY (which is usually…
jdotjdot
  • 16,134
  • 13
  • 66
  • 118
3
votes
1 answer

django AND on Q not working for many to many

Here's the model: class ModelA: title = charfield m2m = foreignkey, relatedname='m2ms' This is working: ModelA.objects.filter(Q(title__icontains='a') & Q(title__icontains='b')) So it returns all records whose titles contains both…
user2349115
  • 1,288
  • 2
  • 17
  • 34
3
votes
2 answers

Defining django queryset with Q objects with foreign key

Example model: class Book(models.Model): title = models.TextField() class Author(models.Model): book = models.ForeignKey(Book) name = models.CharField(max_length=50) and some example data: Book: id title 1 test111 2 test222 3 …
Lukasz Koziara
  • 4,274
  • 5
  • 32
  • 43
3
votes
1 answer

dynamically connecting Django Q objects with AND and OR

I want users to be able to query my database via several different parameters (name, year, etc), dynamically add more fields, and join them with boolean operators; the net result would be something like "year = 1900 AND name = chicken AND location =…
swizzard
  • 1,037
  • 1
  • 12
  • 28
3
votes
1 answer

Django. How Q() really works?

in my database there is a table that holds some user information. The table is called UserBalance and fields include user, credits_in and credits_out and remark (among others) I am trying to sum the credits_in for a certain user but I get different…
xpanta
  • 8,124
  • 15
  • 60
  • 104
3
votes
3 answers

Django ~Q with Joins Functioning Incorrectly. Bug?

We're encountering a very strange problem regarding the negation of Q objects in Django. Let's just use Football as the example: class Team(models.Model): id = UUIDField(primary_key=True) class Player(models.Model): id =…
MatthewKremer
  • 1,549
  • 1
  • 14
  • 25
2
votes
1 answer

Django annotating fields with null values

I have list of Demand objects that have allocated field that would either be null or have a name (denoting this demand's allocation). I use annotations to count allocated/unallocated numbers per…
abolotnov
  • 4,282
  • 9
  • 56
  • 88
2
votes
2 answers

Django model querying for first N rows that sum up to a given number

I am sing Django 3.2 I have a model like this: class MyModel(models.Model): name = models.CharField(max_length=255) num_visits = models.PositiveSmallNumber() created_at = models.DateTimeField() class Meta: ordering =…
Homunculus Reticulli
  • 65,167
  • 81
  • 216
  • 341
2
votes
1 answer

Using Django's Case/When queryset conditions to set more than one value?

I have two values that depend on the same case when condition in my sql call. Currently I duplicate the condition to set each value separately, but can I combine the two identical cases to set both values at once? edit - added an example: …
2
votes
1 answer

Django-Q scheduling tasks every X seconds

I am using Django-Q to schedule a periodic simple task that has to be repeated every < 1 minute. Croniter, used under the hood to parse cron expressions for the scheduler, specifies that cron "seconds" support is…
Shine
  • 3,788
  • 1
  • 36
  • 59
2
votes
1 answer

How to only have one instance of task running in django-q

I created a schedule to repeat a task every 29 minutes with a timeout of 29 minutes using Django-q but when looking at the queued admin view(Using DjangoORM) it has created almost 40+ tasks and going. While having 5 of the same task running…
Marco Fernandes
  • 523
  • 5
  • 19
2
votes
1 answer

How to obtain a list of scheduled Django-Q tasks from a Django View

All, I've implemented Django-Q and Redis and it works great if I use Django Admin to manage everything. Now I'm ready to reproduce the functionality that Django Admin provides from within my app. I'm able manage a schedule tasks but I can't figure…
Gary Franks
  • 103
  • 4
2
votes
1 answer

How to deploy django-q worker with docker?

Assume this simple docker-compose file. version: "3.9" services: redis: image: redis:alpine ports: - 6379:6379 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: …
ondrados
  • 272
  • 3
  • 9
2
votes
2 answers

Django-Q set Q_CLUSTER 'sync': True doesn't work for unit tests

I am using Django-Q to send async emails with Django 2.2, DRF 3.9 and Postgres 10.9 The setup works fine except when it comes to unit tests. I refer to the following issue which is the exact same thing I am…
kbsol
  • 512
  • 6
  • 18