9

I am trying to compare my query search to all my model fields, but I can't figure how to do it in more than one field.

this is my code.

expense = Expense.objects.filter(user=request.user.id).order_by('date')

q = request.GET['q']
result = expense.filter(name__icontains=q)

I want to check in: name, amount, category

Thanks in advance

karthikr
  • 97,368
  • 26
  • 197
  • 188
yaniv14
  • 691
  • 1
  • 10
  • 24
  • If amount is an integer, you will probably won't want to use icontains, but a regular lookup. – Udi Feb 23 '13 at 20:24

1 Answers1

20

From Django documentation:

"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."

from django.db.models import Q
expense.objects.filter(
    Q(name__icontains=q) | Q(amount__icontains=q) | Q(category__icontains=q)
)

I'm not sure about the type of amount and category in your model so icontains may not work on them.

see this link.

jurgenreza
  • 5,856
  • 2
  • 25
  • 37