Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get more than one field with django filter icontains

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

like image 689
yaniv14 Avatar asked Feb 23 '13 20:02

yaniv14


1 Answers

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.

like image 103
jurgenreza Avatar answered Oct 24 '22 00:10

jurgenreza