filter django or

To filter data in Django, you can use the .filter() method. This method allows you to filter the results of a query based on certain conditions.

Here are the steps to filter data in Django using the .filter() method:

  1. Start by importing the model you want to query. For example, if you have a model called Book, you would import it like this:
from myapp.models import Book
  1. Next, use the model's manager to create a query set. This is done by calling the model's manager, which is usually named objects. For example:
books = Book.objects
  1. Use the .filter() method to specify the conditions for the filtering. You can chain multiple filter conditions together to create complex queries. For example, to filter books with a price greater than 10 and published in the year 2020, you can do:
filtered_books = books.filter(price__gt=10, year_published=2020)

In the above example, price__gt=10 means the price should be greater than 10, and year_published=2020 means the year_published should be 2020.

  1. Finally, you can access the filtered results by iterating over the query set, or you can further manipulate the results as needed. For example, to print the titles of the filtered books, you can do:
for book in filtered_books:
    print(book.title)

That's it! By following these steps, you can filter data in Django using the .filter() method. Remember to replace Book with the actual name of your model, and adjust the filtering conditions based on your specific requirements.