Fetch/Retrieve data from database in Django

How to fetch data from database in django?

In django, we retrieve the data in the views.py file, where we write our functions.

To retrieve data from database, first we have to create a url for that. Open the urls.py file inside the application folder, and create a new path as shown below:

    path('students/', views.students, name="students"),

Now create a function in the views.py file, with the name "students" as shown in the above path.

def students(request):
    form = Student.objects.all()
    context = {'form':form}
    return render(request, 'accounts/index.html', context)

Here, we have created a variable form and we have called all the objects of the Student model. Objects is nothing but the records in the database. Then we have created a dictionary named context and passed the form variable in the dictionary and passed that dictionary in the render() function.

As we have mentioned in the render(), let us create a .html file with the name index.html and we will be displaying the all the data in the index.html. To display the data, we will be using the for loop as there will be multiple data in our database.

{% extends 'accounts/layouts/maintemp.html' %}

{% block title %}
All Students
{% endblock title %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1>All Students </h1>
            {% for data in form %}
                {{data.name}}
                {{data.age}}
                {{data.email}}
            {% endfor %}
        </div>
    </div>
</div>

{% endblock content %}

 This will print all the data that we had fetched and stored in the form variable.

Tags: Funda of web it Django tutorials, Django tutorials, Django tutorials funda, django for beginners, how to fetch data from database in django, fetch data in django, django 3 tutorials