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

208 questions
714
votes
14 answers

How can I combine two or more querysets in a Django view?

I am trying to build the search for a Django site I am building, and in that search, I am searching in 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
  • 10,148
  • 8
  • 36
  • 36
113
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
  • 15,691
  • 11
  • 34
  • 41
39
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,069
  • 17
  • 57
  • 106
36
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
  • 491
  • 1
  • 4
  • 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
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
  • 6,577
  • 6
  • 30
  • 35
11
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
  • 8,978
  • 3
  • 32
  • 57
10
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
  • 2,215
  • 3
  • 26
  • 56
9
votes
1 answer

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
  • 938
  • 3
  • 10
  • 22
8
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
  • 584
  • 1
  • 4
  • 17
7
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
  • 71,442
  • 73
  • 210
  • 338
6
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 =…
6
votes
1 answer

Django SQL OR via filter() & Q(): Dynamic?

I'm implementing a simple LIKE search on my Django website and what I currently use is the following code: from django.db.models import Q posts = Post.objects.filter(Q(title__icontains=query)|Q(content__icontains=query)) Where query is a string.…
kovshenin
  • 28,348
  • 4
  • 32
  • 43
6
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
  • 31,751
  • 50
  • 146
  • 233
6
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
  • 30,490
  • 20
  • 83
  • 113
1
2 3
13 14