Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to query data in Django

Shubham Singh Kshatriya

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 LIMIT, TOP, WHERE, etc.

Let’s see some examples of retrieving data in Django.

Create data

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")

Retrieve data

The methods that interact with the database to store, retrieve, update, or delete the data are written inside the file.

Data can be retrieved in the following ways.

1. All data

The all() method returns a QuerySet of all the data present in the database.


2. Specific data using filters

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.

  1. filter(**kwargs): This returns a QuerySet object of the data that matches the given lookup parameter.
  2. 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.



3. Single object

The 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 MultipleObjectsReturned exception.

These are the most common methods to query data in Django. The entire list of QuerySet methods can be found here.




Shubham Singh Kshatriya

View all Courses

Keep Exploring