Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Q objects in django queryset

g = Goal.objects.filter(Q(title__contains=term) | Q(desc__contains=term))

How can I add to my filter that user=request.user?

This doesn't work:

g = Goal.objects.filter(user=request.user, Q(title__contains=term) | Q(desc__contains=term))

Models:

class Goal(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=255)
    desc = models.TextField()
like image 478
user3207076 Avatar asked Jan 17 '14 14:01

user3207076


People also ask

What is Q objects in Django?

Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code. For example, this Q object filters whether the question starts wiht 'what': from django. db.

Why is QuerySet lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.


1 Answers

Keyword arguments (user=request.user) must come after non keyword arguments (your Q object).

Either switch the order in your filter:

Goal.objects.filter(Q(title__contains=term) | Q(desc__contains=term), user=request.user) 

or chain two filter() calls together

Goal.objects.filter(user=request.user).filter(Q(title__contains=term) | Q(desc__contains=term))
like image 141
Alasdair Avatar answered Oct 09 '22 12:10

Alasdair