How to get more than one django filter icon field

I am trying to compare my query search with all fields of my model, but cannot figure out how to do this 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: name, amount,category

Thanks in advance

+5
source share
2 answers

From the Django documentation:

"Queries for keyword arguments are in the filter (), etc. -" AND "together. If you need to perform more complex queries (for example, queries with OR instructions), 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 quantity and category in your model, so the icons may not work for them.

see this link .

+11
source

This works fine, as Jurgenreza replied.

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

All Articles