Last modified: Jan 10, 2023 By Alexander Williams

How to Exclude one or multiple objects from Django Queryset

The exclude() method filter the objects that do not match the given lookup parameters and return a new queryset.

Before using exclude(), let's create a simple model, then add some records.

In models.py:


class Topics(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    
    def __str__(self):
        return self.title

Adding records:

How to Exclude one or multiple objects from Django Queryset

Exclude one object from Queryset

Syntax:


.exclude(field_name="something")

Let's exclude from our model.

In view.py:


def exclude(request):
    topics = Topics.objects.exclude(title="lorem 2")
    #print QuerySet
    print(topics)

    return HttpResponse(topics)

return all objects except that match title="lorem 2".

output:

<QuerySet [<Topics: lorem 1>, <Topics: lorem 3>]>

Exclude multiple objects from Queryset

To exclude multiple objects, we'll use in filter with the exclude() method.

In view.py:


def exclude(request):
    excludes = ['lorem 2', 'lorem 3']
    topics = Topics.objects.exclude(title__in=excludes)
    #print QuerySet
    print(topics)

    return HttpResponse(topics)

output:

<QuerySet [<Topics: lorem 1>]>