Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter vs exclude

Is there a difference between filter and exclude in django? If I have

self.get_query_set().filter(modelField=x) 

and I want to add another criteria, is there a meaningful difference between to following two lines of code?

self.get_query_set().filter(user__isnull=False, modelField=x)  self.get_query_set().filter(modelField=x).exclude(user__isnull=True) 

is one considered better practice or are they the same in both function and performance?

like image 247
Enrico Avatar asked Mar 11 '10 03:03

Enrico


People also ask

What is exclude in Django?

Django's exclude () method basically returns a new QuerySet containing the objects that do not match the given parameter.

What does filter do in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What is difference between filter and get in Django?

Basically use get() when you want to get a single unique object, and filter() when you want to get all objects that match your lookup parameters.

What is QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


2 Answers

Both are lazily evaluated, so I would expect them to perform equivalently. The SQL is likely different, but with no real distinction.

like image 179
Ned Batchelder Avatar answered Sep 16 '22 15:09

Ned Batchelder


It depends what you want to achieve. With boolean values it is easy to switch between .exclude() and .filter() but what about e.g. if you want to get all articles except those from March? You can write the query as

Posts.objects.exclude(date__month=3) 

With .filter() it would be (but I not sure whether this actually works):

Posts.objects.filter(date__month__in=[1,2,4,5,6,7,8,9,10,11,12]) 

or you would have to use a Q object.

As the function name already suggest, .exclude() is used to exclude datasets from the resultset. For boolean values you can easily invert this and use .filter() instead, but for other values this can be more tricky.

like image 23
Felix Kling Avatar answered Sep 17 '22 15:09

Felix Kling