django queryset multiple filters

To apply multiple filters to a Django queryset, you can use the .filter() method along with the desired filter conditions. Each filter condition is separated by a comma. Here is an example of how to do it:

  1. Start with the queryset you want to filter. Let's assume we have a model called Book and we want to filter the books based on their genre and publication year. The initial queryset might look like this:
books = Book.objects.all()
  1. Apply the first filter condition using the .filter() method. For example, let's filter the books by genre. Assuming the genre we want is "Fantasy", we can use the following code:
books = books.filter(genre='Fantasy')
  1. Apply the second filter condition by chaining another .filter() method. For example, let's filter the books by publication year. Assuming we want books published after the year 2010, we can use the following code:
books = books.filter(publication_year__gt=2010)

In this case, publication_year__gt is a filter condition that checks if the publication_year attribute of the book is greater than 2010.

  1. You can continue applying more filter conditions by chaining additional .filter() methods. For example, if you want to filter the books by author, assuming the author's name is "John Doe", you can use the following code:
books = books.filter(author='John Doe')
  1. Finally, you can retrieve the filtered queryset by either iterating over it or converting it to a list. For example, to iterate over the filtered books, you can use a for loop like this:
for book in books:
    # Do something with each book

Alternatively, you can convert the filtered queryset to a list using the .values() method. For example:

filtered_books = list(books.values())

This will give you a list of dictionaries, where each dictionary represents a book object with its attributes and values.

That's it! By following these steps, you can apply multiple filters to a Django queryset.