In Django,QuerySetfiltering allows you to retrieve only the data you need from the database. QuerySets help you filter, sort and organize your data efficiently, making it easy to interact with your models.
This article will explore how to filter datasets using Django’sfilter(),exclude() and advanced filtering withQ objects, let's create a model named "user".
Define the User Model
InprojectApp/models.py, define a User model with fields likeuser_name,city andcountry:
Pythonfromdjango.dbimportmodelsclassUser(models.Model):user_name=models.CharField(max_length=20)city=models.CharField(max_length=20,blank=True,null=True)country=models.CharField(max_length=20,blank=True,null=True)def__str__(self):returnself.user_name
Register the Model in Django Admin
To make the User model accessible in the Django Admin interface, register it inprojectApp/admin.py:
Pythonfromdjango.contribimportadminfrom.modelsimportUseradmin.site.register(User)
Create a superuser to access the model through admin panel.
python manage.py createsuperuser
Suppose we have the following the entries in ourUser model:
Snapshot of the databaseQuerySet Filtering Examples
Now that we have our User model, let’s explore how to filter data using QuerySets.
1. Filtering All Users:
To retrieve all users from a specific country, usefilter():
users = User.objects.filter(country='India')
Thisretrievesall users where the country is 'India':
Snapshot of the command in shell2. Excluding Specific Records:
Toexcluderecords that match a condition, useexclude():
users = User.objects.filter(country='India').exclude(city='Mumbai')
This retrieves all users from India,excludingthose fromMumbai.
Snapshot of shell3. Using Q Objects for Advanced Filtering:
Q objects allow for more complex queries, likeOR conditions:
from django.db.models import Q
users = User.objects.filter(Q(country='India') | Q(city='New York'))
This returns users who are fromeither IndiaorNew York.
Snapshot of shell