'Counting number of rows in the table of mysql database and printing in django webapplication

I have successfully connected Django forms with backend (MySQL) , now I have to count the rows in the table created and print its output in an HTML webpage of my Django web application.

How can I do it?

Picture for Clarification



Solution 1:[1]

on your views.py

def count_rows(request):
    # if you created table with model and migrations
    return render(request, 'your-template.html', {'count': ModelName.objects.count()})

    # if you created table manually
    from django.db import connection
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM table_name WHERE 1")
        count = len(cursor.fetchall)
    return render(request, 'your-template.html', {'count': count})

on your urls.py

# import all from your ```views.py``` file
urlpatterns = [
    # ...
    path('count-rows/',count_rows,name='countrows' ),
    # ...
]

on your template just type this

{{ count }}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1