Q objects in django queryset
Asked Answered
T

3

6
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()
Tobe answered 17/1, 2014 at 14:51 Comment(2)
Please show your models first.Epley
Don't just say, "this doesn't work", please include the traceback. In this case, the traceback is SyntaxError: non-keyword arg after keyword arg, which explains exactly what is going on.Braw
B
12

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))
Braw answered 17/1, 2014 at 15:1 Comment(0)
B
1
g = Goal.objects.filter(Q(user__iexact=request.user) & Q(title__contains=term) | Q(desc__contains=term))

Use & in place of Python and operator

Batfish answered 17/1, 2014 at 15:8 Comment(0)
V
1

According to django docs.

Lookup functions can mix the use of Q objects and keyword arguments. However, if a Q object is provided, it must precede the definition of any keyword arguments.

Valerle answered 23/11, 2017 at 6:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.