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
0
votes
1 answer

ADDing Django's Q() objects and get two exclusive JOIN ONs

So this is the scenario: class Person(models.Model): ... class Aktion(models.Model): ... class Aktionsteilnahme(models.Model): person = models.ForeignKey(Person) aktion = models.ForeignKey(Aktion) The problem now is, that I'm…
nuts
  • 668
  • 8
  • 19
0
votes
1 answer

Django combine two queries without Q

This is the problem I am currently having: I filter out models using Q() and get x results. I then examine x results to determine certain conditions. Depending on those condition, I perform another query and get y results. It's at this point that I…
DGDD
  • 1,168
  • 6
  • 16
  • 31
0
votes
2 answers

Using Q object in list comprehension

I have the following code: def get_elements(self, obj): book_elements = Element.objects.filter(book__pk=obj.id) elements = Element.objects.filter( (Q(book__pk=obj.id) | Q(theme__pk=obj.theme_id)), ~Q(pk__in = [o.element_id for o in…
Zach
  • 3
  • 2
0
votes
1 answer

Querying using Q objects

Hi I'm a newbie to Django. I'm trying to implement a search feature like this. query_results = Shops.objects.filter\ (Q(shop_name__icontains=search_text)\ …
0
votes
1 answer

Django Q filter negating doesn't produce expected query

Simplified Setup class System(models.Model): fields... vulnerabilities = models.ManyToManyField('Vulnerability', through='SystemVulnerability') class Vulnerablity(models.Model): name = ... risk =…
0
votes
2 answers

Q-objects in Django

How can I choose by what var value that I get by filter that then to append a value in the loop? items = Item.objects.filter(Q(var__icontains=term) | Q(another_var__icontains=term)) res = [] for item in items: res.append({ 'val':…
jwshadow
  • 107
  • 10
0
votes
2 answers

NameError while using Q object in a model method

class BlogList(models.Model): title = models.CharField(max_length=100) def get_first_article_image(self): if self.bloglist_articles.exists(): bloglist = self.bloglist_articles.filter( Q(image_link !=…
doniyor
  • 31,751
  • 50
  • 146
  • 233
0
votes
1 answer

How do I use form data generate a custom Q() statement?

I have a search field named q in a form.When I am searching a member, I want it filter like below results = Member.objects.filter(Q(mid=q) | Q(mobile=q)).order_by('pub_date') In other forms I want to do something similar. such as…
Mithril
  • 10,339
  • 13
  • 81
  • 121
0
votes
2 answers

manipulating Q objects, Adding new condition dynamically

I have a Q object like this. params = Q(salt_spray__iregex=keyword) | Q(special_function__iregex=keyword) | Q(comment__iregex=keyword) Here When I filter my model on the basis of this, things work fine. Model.objects.filter(params) But I want to…
A.J.
  • 6,664
  • 10
  • 55
  • 74
0
votes
2 answers

Q queries in Django

If I have the following query return Table.objects.filter(Q(cond1) | Q(cond2)) is there a way to know which condition has given a specific row?
nickbusted
  • 889
  • 2
  • 15
  • 29
0
votes
1 answer

Using Django Q objects in *__lte keywords

I am trying to do this in Django: ThatModel.objects.filter(desired_moisture__lte=Q( F("sensor__moisture") + F("sensor__calibrate_low")) / F("sensor__calibrate_high") + F("upper_deviation")) This is kind of a codeful, so here's what I'm…
Synthead
  • 1,777
  • 4
  • 18
  • 25
0
votes
1 answer

Django Query object Q on multiple fields?

I have a Django model class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) Now I want to search for user. Problem is…
AJ.
  • 110
  • 7
0
votes
1 answer

django q objects and more advanced search

I have a model like this class Customer(models.Model): #fields doctor = models.ForeignKey(Doctor) I wanted to create a search customer form, so I created a new form (not a ModelForm, cause I only wanted the fields of the form not the save…
Apostolos
  • 6,775
  • 14
  • 61
  • 132
0
votes
2 answers

Control Query set in Django (filter,object Q)?

Base On URL querydict = {customer_type:val1,tag:[], city:[],last_contact:valdate} show/?customer_type=All&tag=2,3&city=3&last_contact=29/12/2009 I am going to filter by made the method: def get_filter_result(customer_type, tag_selected,…
kn3l
  • 16,471
  • 26
  • 80
  • 116
0
votes
1 answer

How to make Q queries with models with foreign keys?

my model is defined like this: class Model2(models.Model): id = models.IntegerField(primary_key=True) name = ... class Model1(models.Model): id = models.IntegerField(primary_key=True) model2 = models.ForeignKey(Model2,…
Ladiko
  • 239
  • 2
  • 4
  • 10
1 2 3
13
14