Django 3 : Getting data from the database

Before using Django to retrieve data from a database, we were using SQL queries to retrieve an object containing the result. With Django, there are two ways to retrieve records from the database depending on whether we want to get back one or several records.

Getting multiple records

Step 1 : To retrieve records from a model, we must first import the model into the view as we have done before to save the data in a model. We can retrieve and display all the records in the UserProfile model as follows:

Step 2 : The code template that displays all UserProfile:

Step 3 : Now start the development server with the python manage.py runserver command and open http://127.0.0.1:8000/page/ in your browser.

Step 4 : The all() method can be linked to a SQL SELECT * FROM query. Now, we will use the filter() method to filter our results and make the equivalent of a SELECT * FROM UserProfile WHERE field = value query.

We used a new syntax to send the variables to the template. The locals() function sends all the local variables to the template, which simplifies the render line.

Step 5 : The code template that displays all UserProfile:

Getting only one record

Step 6 : The methods that we will see in this chapter return objects of the Model type, which will be used to record relationships or to modify the instance of the model recovered. To retrieve a single record with a queryset, we should use the get() method as in the following line:

Getting a model instance from the queryset instance

Step 7 : We said that only the get() method makes it possible to retrieve an instance of a model. This is true, but sometimes it can be useful to retrieve an instance of a model from a queryset. For example, if we want to get the first record of the profile admin,