![]() |
VOOZH | about |
QuerySet filtering helps retrieve only the required records from the database, making data handling fast and efficient.
Consider a project named 'projectApp' with a model 'User'. Filtering datasets using Djangoβs filter(), exclude(), and advanced Q objects with a model named User.
In projectApp/models.py, create a User model with fields for user_name, city, and country:
To make the User model accessible in the Django Admin interface, register it in projectApp/admin.py:
To access the User model through the Django admin panel, create a superuser:
python manage.py createsuperuser
Suppose the User model contains the following entries:
With the User model in place, itβs time to explore how to filter data using QuerySets.
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':
To exclude records that match a condition, use exclude():
users = User.objects.filter(country='India').exclude(city='Agra')
This retrieves all users from India, excluding those from Agra.
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.
Code for AND Operation (&):
from django.db.models import Q
# Users who are from 'India' AND live in the city of 'Delhi'
users = User.objects.filter(Q(country='India') & Q(city='Delhi'))
Code for NOT Operation (~):
from django.db.models import Q
# Users from 'India' who are NOT from the city of 'Delhi'
users = User.objects.filter(Q(country='India') & ~Q(city='Delhi'))