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()
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With