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
822
votes
16 answers

How to combine multiple QuerySets in Django?

I'm trying to build the search for a Django site I am building, and in that search, I am searching across three different models. And to get pagination on the search result list, I would like to use a generic object_list view to display the results.…
espenhogbakk
  • 11,508
  • 9
  • 39
  • 38
132
votes
14 answers

How to dynamically compose an OR query filter in Django?

From an example you can see a multiple OR query filter: Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) For example, this results in: [, , ] However, I want to create this query…
Jack Ha
  • 19,661
  • 11
  • 37
  • 41
52
votes
5 answers

django dynamically filtering with q objects

I'm trying to query a database based on user input tags. The number of tags can be from 0-5, so I need to create the query dynamically. So I have a tag list, tag_list, and I want to query the database: design_list =…
babbaggeii
  • 7,577
  • 20
  • 64
  • 118
47
votes
4 answers

Django query filter combining AND and OR with Q objects don't return the expected results

I try to combine AND and OR in a filter using Q objects. It looks like that the | behave like an AND. This is related to the previous annotate which is run in the same query and not as a subquery. What is the correct way to handle this with…
cgaspoz
  • 631
  • 1
  • 5
  • 11
28
votes
3 answers

Django Tastypie Advanced Filtering: How to do complex lookups with Q objects

I have a basic Django model like: class Business(models.Model): name = models.CharField(max_length=200, unique=True) email = models.EmailField() phone = models.CharField(max_length=40, blank=True, null=True) description =…
nknganda
  • 332
  • 1
  • 3
  • 10
19
votes
1 answer

Django queryset filter - Q() | VS __in

What is the difference between queryset.filter(Q(foo='bar') | Q(foo='baz')) and queryset.filter(foo__in=['bar', 'baz']) I'm finding that sometimes they produce different results and I can't figure out why. I'm getting different results with these…
Ross Lote
  • 814
  • 1
  • 8
  • 19
16
votes
1 answer

django Building a queryset with Q objects

I have a form that allows you to pick multiple project types to filter from. For instance, say you have the project types "Research", "Training", and "Evaluation". Basically what I'm looking to do is build a queryset using Q objects…
richard008
  • 403
  • 7
  • 15
14
votes
6 answers

Always True Q object

I want to create some part of Django ORM filter query dinamicly, now I can do: if some: Obj.filter( some_f1=some_v1, f1=v1, f2=v2, f3=v3, f4=v4, ... ) else: Obj.filter( f1=v1, f2=v2, …
Ivan Borshchov
  • 3,036
  • 5
  • 40
  • 62
14
votes
2 answers

how to construct django Q object matching none

I wonder which is the correct way to construct a Q(...) object which matches no object in the queryset. It seems that both Q() and ~Q() match all objects!
Emanuele Paolini
  • 9,912
  • 3
  • 38
  • 64
11
votes
2 answers

Q objects and the '&' operator in django

I have a curious problem. I have 3 objects. All the same class Articles(models.Model): owner = models.ForeignKey(Author) tags = models.ManyToManyField('Tag') class Tag(models.Model): name = models.CharField(max_length=255) and so I…
DantheMan
  • 7,247
  • 10
  • 33
  • 36
11
votes
2 answers

Perform a logical exclusive OR on a Django Q object

I would like to perform a logical exclusive OR (XOR) on django.db.models.Q objects, using operator module to limit the choices of a model field to a subset of foreignkey. I am doing this in Django 1.4.3 along with Python 2.7.2. I had something like…
Marc-Olivier Titeux
  • 1,209
  • 3
  • 13
  • 24
9
votes
3 answers

Django: Extracting a `Q` object from a `QuerySet`

I have a Django QuerySet, and I want to get a Q object out of it. (i.e. that holds the exact same query as that queryset.) Is that possible? And if so, how?
Ram Rachum
  • 84,019
  • 84
  • 236
  • 374
9
votes
3 answers

Negate a Q object in Django

I have a complex Q object created dynamically. How do I negate the Q object so that it can be used in filter() instead of exclude()?
ATOzTOA
  • 34,814
  • 22
  • 96
  • 117
8
votes
1 answer

Using Django's CheckConstraint with annotations

I have a Django model where each instance requires a unique identifier that is derived from three fields: class Example(Model): type = CharField(blank=False, null=False) # either 'A' or 'B' timestamp =…
8
votes
1 answer

'Q' object has no attribute 'split' - Django

I have a Model: class Authors(models.Model): name = models.TextField() person = models.ForeignKey(Person) and query: authors = Author.objects.filter( (Q(name__iregex=r"\y{0}\y".format(s1)), …
doniyor
  • 36,596
  • 57
  • 175
  • 260
1
2 3
16 17