0
0
Djangoframework~5 mins

exclude() for negation in Django

Choose your learning style9 modes available
Introduction

The exclude() method helps you get all items that do NOT match certain conditions. It is like saying "give me everything except these".

You want to find all users except those who are inactive.
You want to list all products except those that are out of stock.
You want to show all blog posts except those written by a specific author.
You want to filter out certain categories from a list of items.
Syntax
Django
Model.objects.exclude(field=value)

exclude() returns a QuerySet without the records matching the condition.

You can chain multiple exclude() calls or combine with filter().

Examples
Gets all users who are active (not inactive).
Django
User.objects.exclude(is_active=False)
Gets all products that have stock available.
Django
Product.objects.exclude(stock=0)
Gets all blog posts except those written by the user 'admin'.
Django
BlogPost.objects.exclude(author__username='admin')
Sample Program

This example shows how to get all products that have stock available by excluding those with zero stock.

Django
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    stock = models.IntegerField()

# Imagine we have these products in the database:
# Product(name='Pen', stock=10)
# Product(name='Notebook', stock=0)
# Product(name='Eraser', stock=5)

# Query to get all products that are NOT out of stock
available_products = Product.objects.exclude(stock=0)

for product in available_products:
    print(product.name)
OutputSuccess
Important Notes

exclude() is the opposite of filter(). Use it when you want to remove certain records.

You can use double underscores to filter on related fields inside exclude().

Summary

exclude() helps you get all records except those matching a condition.

It is useful to remove unwanted items from your query results.

You can combine exclude() with other QuerySet methods for flexible queries.