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
2
votes
2 answers

Django Q Queries & on the same field?

So here are my models: class Event(models.Model): user = models.ForeignKey(User, blank=True, null=True, db_index=True) name = models.CharField(max_length = 200, db_index=True) platform = models.CharField(choices = (("ios", "ios"),…
Chase Roberts
  • 9,082
  • 13
  • 73
  • 131
2
votes
0 answers

django Q as chained .filter()

There are 2 models connected with a many-to-many relationship. class Record(): working_on_record = models.ManyToManyField( UserProfile, related_name="working_on_record", blank=True) class UserProfile(): name = CharField... The…
Jehob
  • 101
  • 7
2
votes
1 answer

Filter by user is not staff using Q in another model queryset

I have the following model: class APC(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='apc', on_delete=models.SET_NULL) type= models.CharField(choices=TYPE_CHOICES, max_length=5,…
user3541631
  • 3,686
  • 8
  • 48
  • 115
2
votes
1 answer

Filtering Django QuerySet based on ManyToMany relationship existence

The Models Here is the basic models setup we have. A List has many Items, and an Item can be in many Lists. For a given Item, if any of its Lists are good (i.e., list.bad == False) then the Item is good. If an Item doesn't appear in any good Lists,…
2
votes
0 answers

Django+JS -- toggling filter views

Currently, the Django project I am working on has, among other things, functionality to upload a "blackbox" file that gets converted to "datapoints" (list of Python dicts) as well as to filter through a blackbox to display only certain datapoints…
Dan K
  • 803
  • 8
  • 26
2
votes
2 answers

Multiple ManyToMany 'in' query with Django

I've simplified the models for the question, but essentially I'm trying to perform a query with the following models: class mod1(models.Model): mod1_id = CharField(unique=True, ...) class mod2(models.Model): field2 =…
Wolf
  • 63
  • 5
2
votes
2 answers

Django Q objects and m2m queries

I'm totally flummoxed by this behavior. I clearly don't understand Q objects like I thought I did or I'm doing something massively stupid and obvious. Here's what I'm running into. accepted_attendee_* are all m2m relationships to OfficialProfile.…
ghiotion
  • 285
  • 5
  • 12
2
votes
1 answer

TypeError: unsupported operand type(s) for |: 'bool' and 'Q'

I'm running Django 1.7 and I'm getting TypeError: unsupported operand type(s) for |: 'bool' and 'Q' when trying to do the following: class PersonList(generic.ListView): template_name = "persons/list.html" model = Person queryset =…
SaeX
  • 17,240
  • 16
  • 77
  • 97
2
votes
1 answer

Django Q object not working

I want to make a or query with Django filters. The code I have seems easy but it does not work. I have read a lot for answers but nothing worked for me. What is the fault? from django.db.models import Q from models import Processoren cpu = [ …
Sanderr
  • 149
  • 1
  • 1
  • 8
2
votes
1 answer

How to generate a combined Q object from a list?

I have a list of dictionaries with app_label and model keys that I got from the ContentType model: model_list = [ { 'app_label': 'store', 'model': 'product', }, { 'app_label': 'store', 'model': 'profile', …
austinheiman
  • 939
  • 1
  • 12
  • 17
2
votes
2 answers

How to filter Many2Many / Generic Relations properly with Q?

I have 3 Models, the TaggedObject has a GenericRelation with the ObjectTagBridge. And the ObjectTagBridge has a ForeignKey to the Tag Model. class TaggedObject(models.Model): """ class that represent a tagged object """ tags =…
HWM-Rocker
  • 587
  • 2
  • 8
  • 17
2
votes
2 answers

Combine Q objects in Django and limit one of them

I want to combine these 2 queries in 1 to get the Music object with name xyz and also get top 3 objects from genre 10, ordered by artist: 1. Music.objects.filter(name='xyz', genre=10) 2. Music.objects.filter(genre=10).order_by('artist')[:3] I can…
click
  • 2,093
  • 2
  • 15
  • 21
2
votes
1 answer

Django Q bad query logic

I'm trying to create a manager that has a method 'active_or_users' to retrieve all accounts that are active, or that an user has created. An active account has a start date that is either today, or somewhere in the past, and a end date that is…
user133688
  • 6,864
  • 3
  • 20
  • 36
2
votes
1 answer

How can I use Django Querysets and Q() to compare against objects of the same model type?

I have a Django model named MyModel. m is an instance of MyModel. I would like to use Django QuerySets to find all the instances of MyModel that are not m. How to do it? This doesn't work: MyModel.objects.filter(~Q(m)) It seems you can query…
Saqib Ali
  • 11,931
  • 41
  • 133
  • 272
2
votes
3 answers

Different results on query changing Q object order

I have a problem when making a queryset using Q objects. I'm getting different results depending on how i order some Q conditions. I will simplify my models a little so as to describe my problem in a clean way. class D(models.Model): one_attr =…
marianobianchi
  • 8,238
  • 1
  • 20
  • 24