Django Q objects

By: Priya Philip 3 weeks, 5 days ago

Q objects (django.db.models.Q) is an object used to encapsulate a collection of keyword arguments.

from django.db.models import Q

 Q objects can be combined using the & and | operators.

Q(name__startswith='p') | Q(name__startswith='r')
Which is equivalent to the  SQL WHERE clause:
WHERE name LIKE 'p%' OR name LIKE 'r%'

Q objects can be negated using the ~ operator, allowing for combined lookups that combine both a normal query and a negated (NOT) query:

 Q(name__startswith='p') | ~Q(start_date__year=2005)

If you provide multiple Q object arguments to a lookup function, the arguments will be “AND”ed together. For example:

    Q(start_date=date(2019, 5, 2)) | Q(start_date=date(2019, 5, 6))

This is equal to SQL statement:

SELECT * from course WHERE name LIKE 'p%'
    AND (start_date = '2019-05-02' OR start_date = '2019-05-06')


Wish to hire us?

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.