Django Python Projects 2023

How do I do a not equal in Django Queryset filtering with code example?

In Django queryset filtering, you can use the exclude() method to perform a not equal operation on a specific field. The exclude() method returns a queryset that excludes the objects matching the specified conditions. Here’s an example of how to use it:

Assuming you have a model named Person with a field named age, and you want to exclude people whose age is not equal to a certain value, you can do it like this:

from yourapp.models import Person

# Filter out people whose age is not equal to 25
not_equal_age_people = Person.objects.exclude(age=25)

# Iterate through the queryset to see the results
for person in not_equal_age_people:
print(person.name, person.age)

In this example, the exclude() method is used to retrieve all Person objects whose age is not equal to 25. You can replace age=25 with the condition you want to use for inequality.

Remember that you can chain multiple conditions using the exclude() method. For instance, if you want to exclude people whose age is not equal to 25 and whose gender is not ‘Male’, you can do:

not_equal_age_and_gender_people = Person.objects.exclude(age=25, gender='Male')

By chaining conditions with exclude(), you can construct complex queries to filter out objects that don’t match certain criteria.

admin

Recent Posts

MERN stack web development projects for students

MERN Stack Web Development Projects for Students Orphan Helper & All-in-One Donation Platform The MERN stack — MongoDB, Express.js, React.js,…

8 months ago

Full-stack React.js project ideas with Node.js and MongoDB

Full-Stack React.js Project Ideas with Node.js and MongoDB Disaster Helper, Community Connect When building full-stack applications, combining React.js for the…

8 months ago

Best React.js web development projects for students

Best React.js Web Development Projects for Students Education Equality, Lost and Found Items, Tour Package React.js is one of the…

8 months ago

Top React.js final year project ideas with source code

Top React.js Final Year Project Ideas with Source Code Agri Insurance and Hospital Management As the demand for modern web…

8 months ago

Trending React.js projects for 2025

Trending React.js Projects for 2025 Innovative Ideas for Modern Web Development React.js has undoubtedly emerged as one of the most…

8 months ago

Mern Stack Project topics with source code

MERN Stack Project Topics with Source Code The MERN stack (MongoDB, Express.js, React.js, and Node.js) is a popular technology stack…

8 months ago