ADVERTISEMENT
ADVERTISEMENT

Django – How to filter empty or NULL names in a QuerySet?

Given a QuerySet, we have to filter empty or NULL names.
Submitted by Apurva Mathur, on May 26, 2022

Let's begin the solution to this problem by learning about Django QuerySet Filter.

What is QuerySet in Django?

A QuerySet is a collection of data from the database, it is built up of a list of objects, and it helps us by allowing us to filter and order the data.

Filtering QuerySets dynamically via code is something that makes our app more hassle-free. The filter() method is used to filter searches and allows us to return only the rows that match the search term.

Example:

data = newtable.objects.filter(department='computer_science')

In SQL it conveys that:

SELECT * FROM newtable WHERE department='Computer_science';

This will purely select all the data whose department is computer science.
If we want more than one argument in this filter function we can cleanly do that by using keyword arguments that will make this function filter on more than one field by separating them by a comma.

Example:

data= newtable.objects.filter(roll_number='191052', id=1);

In SQL it conveys that:

SELECT * FROM newtable WHERE roll_number='191052' AND id=1;

This query will provide the data from newtable whose roll_number = 191052 and id =1.

Let's see how can we filter the data when is field has NULL values.

Situation 1:

Imagine a situation where you want to search the name in a table whose roll_no value is null. We can achieve this by writing the following code:

name.objects.filter(roll_no__isnull=True)

Situation 2:

When there isn't a specific field lookup to locate empty files (such as string fields that contain nothing but are not NULL in the database, in this case we can approximate this functionality with the exact field.

Example:

name.objects.filter(department__exact='')

In the above example, we'll get the data whose name is specified but the department column has no value (empty string).

Situation 3:

If we want to possibly eliminate those names with either the NULL roll_no or an empty department, in this case, we can use exclude() function with the filter() function.

Example:

name.objects.exclude(roll_no__isnull=True).exclude(department__exact='')
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.