In order to query data from the database in Django, we need to use the Manager of the model class to create a QuerySet. Each model class has at least one Manager.
A QuerySet refers to a collection of objects with zero or many filters. In comparison to SQL, a QuerySet is equivalent to the
SELECT statement, and the filters are equivalent to limiting clauses like
Let’s see some examples of retrieving data in Django.
In order to retrieve data, let’s first create some dummy objects with the model we made here.
Product.objects.create(name="Nike Airforce", price="199") Product.objects.create(name="Adidas EQT", price="149") Product.objects.create(name="Tesla", price="2000") Product.objects.create(name="Iphone 13", price="899") Product.objects.create(name="Pen", price="10")
The methods that interact with the database to store, retrieve, update, or delete the data are written inside the
Data can be retrieved in the following ways.
all() method returns a QuerySet of all the data present in the database.
Filters are conditions added in order to limit the data and can be chained together. Each returned QuerySet object is unique and distinct and can be stored or reused.
Below are the two most common methods.
filter(**kwargs): This returns a QuerySet object of the data that matches the given lookup parameter.
exclude(**kwargs): This returns a QuerySet object of the data that does not match the given lookup parameter.
kwargs are keyword arguments that serve as the lookup parameters.
Both methods will return the same QuerySet object. The first method selects all the data where the price is less than 500, while the second one excludes data where the price is greater than or equal to 500.
get() method returns a single object that matches the lookup parameter.
If there is no data that matches the lookup parameter,
get() will raise the
DoesNotExist exception. If there is more than one data that matches the lookup parameter, the method will raise the
These are the most common methods to query data in Django. The entire list of QuerySet methods can be found here.
View all Courses