How to Remove Results from a QuerySet in Django



Python


In this article, we show how to remove results from a QuerySet in Django.

Let's say that you're querying a database for certain values. Let's say that you have a databases that contains posts for a website and a user types in the query, 'exercise'. This will return all posts that have a title or content that contains the word, 'exercise'.

Let's say that's your initial query. However, let's say the user wants to now only check results that contain the word, 'exercise', that has been published this year.

We can use the exclude() function in Django to exclude certain results from an initial query.

Let's say we have a model and we want to exclude posts that were written in 2015.

The code for this is shown below.



The code above will exclude all posts that were written in 2015.

We go through another, more complicated example beslow.

So below is code that queries a database for whatever the user has entered in and checks to see if there is any post that has a title or content with that query.



So now we'll fully go through the code.

So we import the Post model.

We then get the query that the user has entered.

We then have a lookups so that we can return a post that has a title or content that contains the query.

We then have a variable, results, that returns all the unique posts that contain the query.

Now is where we use the exclude() function to remove all objects of the QuerySet that weren't published this year (which is 2019). By using the exclude() function and putting inside, year < 2019, this excludes all posts that were written before 2019.

So the exclude() function is very variable, if you want to exclude certain results from an initial QuerySet.

This may be necessary for all types of purposes.

When you're creating dynamic search capability for a website, you may have to do an initial query first to get an initial QuerySet of results returned. Afterwards, you may need to exclude results based on the query that the user has entered. So using the exclude() function on a QuerySet is very valuable.

And this is how to remove results from a QuerySet in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...