Read or Retrieve Data from Database in Django

Sometimes using database views rather than database tables can be very helpful for querying aggregated data. Typically in the Django ORM, a database table is tied to a Django ORM model, but we found it is also possible to tie a database view with a Django ORM model. By doing so, you can hide the data aggregation logic on the database level (in view creating SQL).

And most of the ORM features, like double underscore foreign key lookup, still work for the model tied to a database view. 

Django Model Example Overview

We will be doing the following in this Django ModelForm Example

  • Create a Page for entry of Student Details(StuID, Name, Email-id, Password) and save it into the database(which will be done automatically by model forms).
  • Create the student details page where we would view the student entries in an ordered list.

Coding the App

As usual, we need to deal with some data(No, Name, Age, Mob No, Address). So, we need to create the model of the data and implement that model into the sqlite db of django.

To do so, look for the file models.py in your app folder and add the code below:-

from django.db import models

# Create your models here.
class Student(models.Model):
    stuid = models.IntegerField()
    stuname = models.CharField(max_length=70)
    stuemail = models.EmailField(max_length=70)
    stupass=models.CharField(max_length=70)
  • Add your app in the installed apps of settings.py

Making Migrations

  • Make sure that the shell is navigated into the correct folder and run the following command.
python manage.py makemigrations
  • Next, run the command below to actually implement it into the database.
python manage.py migrate
  • By now, the database is created into the SQLite DB.

Configuring the View

  • Yes, the class based views reduce our efforts to quite an extent.
  • So, look for the file views.py in your app folder and add the following code:
from django.shortcuts import render
from enroll.models import Student
# Create your views here.

def studentinfo(request):
    stud = Student.objects.all()
    print("Myoutput",stud)
    return render(request,'enroll/studetails.html',{'stu': stud})

Creating UI for Django Model

  • Firstly create a directory named templates into your app folder.
  • Now, in the templates folder, create another directory named enroll and it should be like /Your_app_name/templates/enroll/.
  • In the Your_app_name folder present in templates directory, create a new HTML file called Studentdetails.html and add the following code:-
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Document</title>
    <style>
        th,td{
        border: 1px black solid;
        }
    </style>
</head>
<body>
 <h1>Student Page</h1>
{% if stu %}
 <h1>Show Data</h1>
 <h3>{{stu}}</h3>
 <table>
     <tr>
         <th>ID</th>
         <th>StuID</th>
         <th>Name</th>
         <th>Email</th>
         <th>Password</th>
     </tr>
 <tr>
     {% for st in stu %}
     <td>{{st.id}}</td>
     <td>{{st.stuid}}</td>
     <td>{{st.stuname}}</td>
     <td>{{st.stuemail}}</td>
     <td>{{st.stupass}}</td>
 </tr>
     {% endfor %}
</table>
{% else %}
 <h1>No Data</h1>
{% endif %}
</body>
</html>

Running the app

  • To add, edit and delete the posts we’ve just modeled, we will use Sqlite3 and add details in your database.

  • You can also create a superuser to add data to the database. Then make add the following code in the admin.py file
from django.contrib import admin

# Register your models here.
from enroll.models import Student
admin.site.register(Student)

Hence, now on running the server/admin you can see that your app is present on the admin panel:

Now you also add data using the admin panel by opting for “Add Student” option and can also check the details of the student enrolled:

  • Now lets try running the app. Make sure your development server is running. If not you can use the following command in your Windows PowerShell to run your development server.
python manage.py runserver

  • If you want to retrieve a specific data from the table then you need to make the following changes in views.py and studentdetails.html

views.py 

from django.shortcuts import render
from enroll.models import Student
# Create your views here.

def studentinfo(request):
    stud = Student.objects.get(pk=1)
    print("Myoutput",stud)
    return render(request,'enroll/studetails.html',{'stu': stud})

studentdetails.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Document</title>
    <style>
        th,td{
        border: 1px black solid;
        }
    </style>
</head>
<body>
 <h1>Student Page</h1>
{% if stu %}
 <h1>Show Data</h1>
 <h3>{{stu}}</h3>
 <table>
     <tr>
         <th>ID</th>
         <th>StuID</th>
         <th>Name</th>
         <th>Email</th>
         <th>Password</th>
     </tr>
 <tr>
     <td>{{stu.id}}</td>
     <td>{{stu.stuid}}</td>
     <td>{{stu.stuname}}</td>
     <td>{{stu.stuemail}}</td>
     <td>{{stu.stupass}}</td>
 </tr>
</table>
{% else %}
 <h1>No Data</h1>
{% endif %}
</body>
</html>

Here, we are retrieving ID 1 data, so the output will be: