Django is one of the most popular web development frameworks in Python, providing developers with the ability to rapidly create powerful web applications. An essential and very important part of Django is the ORM (Object-Relational Mapping) system, which allows you to easily interact with various databases without having to directly use SQL.
One of the key concepts in this ORM system is called QuerySet. This concept allows you to retrieve data from the database using Python methods and filters. It can be said that a QuerySet is a list of objects that are selected or filtered.
When working with QuerySet, you have a model interface that is abstracted and can be powerful for you. Everything you need allows you to use this model as a guide to translate SQL behavior that translates your requests into the database's native language and also provides the same result back in an easily usable form with Python.
Therefore, if you continue working with database systems and need to write queries in SQL, in Django, instead of writing direct queries, you can make use of QuerySet to easily retrieve the same results.
Here is an example of how to use QuerySet to filter data in Django models:
from myapp.models import Book
# Get all books
books = Book.objects.all()
# Filter books by title
titled_books = Book.objects.filter(title='Django Unleashed')
# Get a single book by primary key
book = Book.objects.get(pk=1)
In the above example, Book.objects.all()
retrieves all objects in the Book model.
Book.objects.filter(title='Django Unleashed')
filters and retrieves all books whose title is 'Django Unleashed'.
Book.objects.get(pk=1)
retrieves the book whose primary key is 1.