How to Filter Database Results in Django



Python


In this article, we show how to filter database results in Django.

Say, you have a table with rows and rows of data. You want to find the row that has students whose first name is Michael.

With Python, you can filter out the table so that only results of students whose first name is Michael is returned in search results.

We can do this in the database API in Django or in actual Python code in a file- it doesn't matter.

So, let's say we have a table named Students that contains the first name, last name, and email address of students.

Again, like before, let's say we want to filter results out so that only students whose first name is Michael gets returned.

The code to do this would be that shown below.



Since I have a student named Michael Robertson in the database, this returns the following result.



Say, if you want to find out which student is at the id of 1.

The code to do this is shown below.



Since the first student in the database table I created is Joyce Peters, I get the following result sent back.



There are infinite ways you can filter results using Python in Django.

For example, to find students whose email ends with gmail.com, you would use the __endswith statement, shown below.



This will return all students whose email ends with gmail.com, thus, it will show students who have gmail accounts.

If you want to find all students whose last names begins with P, the code to do so would be that shown below.



If you filter out results in Django and there is no results, then there would be an empty queryset returned.

For example, if you want to check students whose email accounts ends with yahoo.com and no students have yahoo email accounts, then you would an empty set.

You would get the following result returned.



So, you can see there's so many ways to filter database results using Python in Django.

This is important because you have databases so that you can filter out results and get the ones that you want. So filtering database results is a crucial when dealing with databases.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...