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
1
vote
1 answer

Mock async_task of Django-q

I'm using django-q and I'm currently working on adding tests using mock for my existing tasks. I could easily create tests for each task without depending on django-q but one of my task is calling another async_task. Here's an example: import…
1
vote
0 answers

Django updating One-To-One Relationship is causing UNIQUE Constraint Failure

I cannot wrap my head around why I'm getting an error here - when the update query is run with this django ORM save() code, I get a UNIQUE Constraint Error: django.db.utils.IntegrityError: UNIQUE constraint failed: tasks_recurringtask.id From my…
Borzi
  • 537
  • 1
  • 5
  • 21
1
vote
1 answer

Need to annotate Django querySet based on which Q object was found

So I have a query with a few Q objects that are OR-ed together (to achieve a UNION), and I want to annotate each result with which Q object was a match. This is so when I go to display my query results, I can highlight which search term(s) were hits…
nmz787
  • 1,960
  • 1
  • 21
  • 35
1
vote
1 answer

Django Q object not chaining correctly

I'm querying a ManyToMany field (tags). The values come from a list: tag_q = Q() tag_list = ["work", "friends"] for tag in tag_list: tag_q &= Q(tags__tag=tag) Post.objects.filter(tag_q) When I have only one value, it works flawlessly, but…
andrepz
  • 443
  • 6
  • 16
1
vote
1 answer

Django-q how to delete scheduled tasks from code

I use django-q to schedule a periodic task associated an entry in my model Repository (code here after). But when I delete a Repository entry, the associated Schedule entry is not deleted, and so the django-q jobs associated is not cancelled. Any…
jery
  • 31
  • 3
1
vote
0 answers

django_q_task saves too much records

I am having a problem with my djang_q_task table. It saves too many records than expected. I have config like below: Q_CLUSTER = { 'name': 'xxxx', 'workers': 8, 'recycle': 500, 'timeout': 600, 'compress': True, 'save_limit':…
van thanh tran
  • 177
  • 2
  • 11
1
vote
0 answers

Django ORM - selecting related records by setting criteria on some fields but excluding current record from returned records

I am using Django 3.2 I am writing a function to return related records when an object is retrieved from the database. I am using the tags field (a TaggitManager instance) to determine which records are related. I then want to remove (i.e. exclude…
Homunculus Reticulli
  • 65,167
  • 81
  • 216
  • 341
1
vote
2 answers

Django-q how to delete scheduled tasks

I'm using django-q to schedule monthly event for sending emails. After several testing runs, I realized that each time I execute the: Schedule.objects.create(func='app.email.send_monthly_email',schedule_type=Schedule.MONTHLY,repeats=-1) this…
minda
  • 13
  • 3
1
vote
1 answer

Q model and or query giving incorrect result

I want perform below SQL query using Q models SELECT * FROM motor_vehicle_collision.collision_data_collisiondetails where (numberOfCyclistInjured > 0 or numberOfCyclistKilled > 0) and (longitude != '' and latitude != ''); for that I have written…
LowCool
  • 1,187
  • 5
  • 25
  • 51
1
vote
1 answer

Django-Q and request.POST data

I have a budget app I am working on and using Django and Django-Q. I want to create a schedule to post automatically an expense based on a Django-Q schedule I create. The issue I am having is understanding the logic of using three positional…
Tony
  • 13
  • 3
1
vote
1 answer

Store keywords in queryset that give search hits with Q objects in the resultant queryset along with the search results

record_list is a Python list containing a list of keywords to be searched. The following code is my Django views.py where I am searching the MySQL database using these keywords. The code searches in columns product_name and description and returns…
User
  • 11
  • 1
1
vote
2 answers

Querying Parent from the foreign key django

I have the following models : class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=32) is_staff =…
1
vote
0 answers

How to upgrade Django Q and Django without clearing the queue?

When deploying the project after upgrading Django and Django-Q. I got the following log. Is there a way to avoid that error but still keep the tasks running in the queue to avoid downtime? 08:59:03 [Q] INFO Process-1:440 pushing tasks at…
HoangYell
  • 4,100
  • 37
  • 31
1
vote
1 answer

Schedule ignors kwargs in django-q

I am using Django-q (https://django-q.readthedocs.io) for queuing in the Django framework. I have an async function when I use async_task: async_task('sms.tasks.send', username=username, …
Amin.B
  • 117
  • 2
  • 9
1
vote
1 answer

Filtering a many-to-many relationship with Django's Q query

I have a model class Book(models.Model): title = models.CharField(max_length=200) authors = models.ManyToManyField(Author) class Author(models.Model): first_name = models.CharField(max_length=30) last_name =…
user8954282