Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to not include the data from DB in the multiple icontains condition in model filter?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading