I'm currently developing an application using Django
.
I want to use multiple icontains
condition in filter
using Q
as shown below.
but in this case, If either target_1
or target_2
is an empty string
(''
), all the data is gotten.
queryset = MyModel.objects.filter(Q(my_field_1__icontains=target_1)| Q(my_field_2__icontains=target_2)).all()
But I don't want to include it in the data if the value of either target becomes an empty string.
How can I enable it only if they do not include the empty string and contains other values?
Python: 3.7.5
Django: 3.2.
CodePudding user response:
You can work with dictionary comprehension to filter out empty values:
data = {'my_field_1__icontains': target_1, 'my_field_2__icontains': target_2}
data = {k: v for k, v in data.items() if v}
if data:
queryset = MyModel.objects.filter(Q(**data, _connector=Q.OR))
else:
queryset = MyModel.objects.none()
the if data
checks if there is at least one item with a non-empty string. If that is not the case, we return an empty queryset.