How to Search Multiple Columns of a Database Table in Django with Q Objects



Python


In this article, we show how to search multiple columns of a database table in Django with Q objects.

Q objects can be used with boolean & (and) or | (or) statements to have multiple conditions expressed within a single lookup.

So below is the views.py file for the a lookup with Q objects.



So the first thing we have to do is import Q from django.db.models

In this code, we have a database table (or model) named Post. This model has the fields: title, slug, content, pub_date, last_edited, author, likes, and dislikes.

We want to be able to use a search form to search whether the title contains the query that the user has entered or the content contains the the query that the user has entered.

Therefore, we use 2 Q objects, which forms a single Q object.

We look to see whether the title of the post contains the query or the content of the post contains the query. If either does, that post is returned in the filter function. Thus, you can see how the Q object gives us the ability to search multiple columns of a database table in Django.

The Q object allows for complete customization when doing searches of a database table in Django. And it's ideal for things such as advanced searches, which involve multiple fields.

Just as a reference, below is the model we searching for the above field.



This just shows you the structure of the database table.

And, for reference as well, this is the template file which has the search form.



This just gives more reference to this Q object, so that the views.py file makes more sense.

And this is how we can search multiple columns of a database in Django with Q objects.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...