Python Django Queryset Filtering (original) (raw)
Last Updated : 22 May, 2025
In Django, **QuerySet **filtering 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’s **filter(), **exclude() and advanced filtering with **Q objects, let's create a model named "**user".
Define the User Model
In **projectApp/models.py, define a User model with fields like **user_name, **city and **country:
Python `
from django.db import models
class User(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):
return self.user_name
`
Register the Model in Django Admin
To make the User model accessible in the Django Admin interface, register it in **projectApp/admin.py:
Python `
from django.contrib import admin from .models import User
admin.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 our **User model:
Snapshot of the database
QuerySet 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, use **filter():
users = User.objects.filter(country='India')
This **retrieves all users where the country is '**India':
Snapshot of the command in shell
2. Excluding Specific Records:
To **exclude records that match a condition, use **exclude():
users = User.objects.filter(country='India').exclude(city='Mumbai')
This retrieves all users from India, **excluding those from **Mumbai.
Snapshot of shell
3. Using Q Objects for Advanced Filtering:
**Q objects allow for more complex queries, like **OR conditions:
from django.db.models import Q
users = User.objects.filter(Q(country='India') | Q(city='New York'))
This returns users who are from **either India or **New York.
Snapshot of shell