Django 3 : Getting data from the database

Louis SanchezApril 17th 2021, 7:10

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:

from django.shortcuts import render
from myproject.models import UserProfile

def page(request):
    all_user_profile = UserProfile.objects.all()
    return render(request, 'page.html', {'action': "Display all UserProfile", 'all_user_profile': all_user_profile})

Step 2 : The code template that displays all UserProfile:

{% extends "base.html" %}
{% block title %}
  {{ action }}
{% endblock %}
{% block h1 %}
  {{ action }}
{% endblock %}
{% block content %}
  {% if all_user_profile|length > 0 %}
  <table>
    <thead>
      <tr>
        <td>ID</td>
        <td>Name</td>
      </tr>
    </thead>
    <tbody>
    {% for profile in all_user_profile %}
      <tr>
        <td>{{ profile.id }}</td>
        <td>{{ profile.name }}</td>
      </tr>
    {% endfor %}
    </tbody>
  </table>
  {% else %}
  <span>No data.</span>
  {% endif %}
{% endblock %}

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.

profile_admin = UserProfile.objects.filter(name="admin")

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:

<table>
    <thead>
        <tr>
        <td>ID</td>
        <td>Name</td>
        </tr>
    </thead>
    <tbody>
    {% for profile in profile_admin %}
        <tr>
        <td>{{ profile.id }}</td>
        <td>{{ profile.name }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

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:

first_profile = UserProfile.objects.get(id="1")

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,

queryset_profile = UserProfile.objects.filter(name="admin").order_by("id")
# This line returns a queryset in which there are as many elements as there are profiles for the admin

first_item_queryset = queryset_profile[:1]
# This line sends us only the first element of this queryset, but this element is not an instance of a model

profile = first_item_queryset.get()
# This line retrieves the instance of the model that corresponds to the first element of queryset