pythondjangodjango-modelsfrontenddjongo

Showing data on frontend from sql databases using django


For fetching data from databases, I usually see people create a class in models.py and they migrate it, and then they fetch data from databases and show it on the front-end. my question is, i already have a database which has student_info table and has lots of data. I don't want to define student_info class in models.py and do migration. Instead, since i already have student_info data in sql database. so I want to fetch it directly. can i do so?

one method i know of doing the same, is directly connecting sql server in views.py as;

mydb=mysql.connector.connect(host="localhost",user="root",password="******",database=database_name)

and fetching the data and passing it as variable in index.html. But the problem is, it fetches data only once, and if i refresh the page where local server is running, all the content will disappear, and server will report Broken pipe from ('127.0.0.1', 59579) and to see the data, again i need to restart the sever.

Kindly looking for a better approach to show data on front-end from the existing databases


Solution

  • What you could do is a simple thing for the solution.

    Create a StudentData(models.Model) class which will store your data in them as model objects And define all the attributes/ columns in models according to the data and which is in the student_info table.

    Write a simple script ( using pymysql ) to retrive all the data from the student_table , store it in text file . ( This part is easy )

    take that text file and now in your django project , run a shell command or create a new script to transfer the text_file student data to model objects and save them . Now you have your data .

    I think this will work fine . If you also want code . I'll include it.

    The code for the solution :

    An Update : I have used pymysql for this scripts , i think mysqlconnector will also do the work.

    Create a folder inside your project named "Creating Database model" ( you can choose whatever you want but I created the files and all script inside this folder )

    first_file : "data retreiving.py"

    import pymysql as psql
    import os
    connection = psql.connect(
        user = "root" , 
        password = os.environ.get("MYSQL_PASSWORD") , 
        database = "college" ,    
    )
    cursor = connection.cursor()
    cursor.execute("select * from student") ;
    data_text_file = open("Creating Database model/text_data.txt" , "w")
    
    for row in cursor :
        temp_string = ""
        for data in row :
            temp_string+= "{} ".format(str(data)) 
        data_text_file.write(temp_string+"\n")
    data_text_file.close()
    

    Enter your password for connection. Here I am using college database which has student table with some student data . Then I am creating a file text_data.txt which will have the text data of the table . I used string formatting here for convinence and better retrival of data on the other side.

    My student table schema has five fields : id , first_name, last_name , age , branch

    so my models.py according to this database is here . You create your own according to your requirement.

    from django.db import models
    
    class StudentData(models.Model) :
        first_name = models.CharField(max_length = 100 , required = True)
        last_name  = models.CharField(max_length = 100 , required = True)
        age        = models.IntegerField(max_length = 100 , required = True)
        branch     = models.CharField(max_length = 100 , required = True)
        
        def __str__(self) :
            return "{} {}".format(first_name , last_name)  
    

    second file : "data entry in models.py"

    This file takes data and then saves it to the model . And you get your database in django .

    with open("Creating Database model/text_data.txt") as f :
        data = f.read()
        
    new_data_list = []
    
    data = data.split("\n")
    new_data_list = []
    for i in data :
        temp_list = i.split(" ")[:-1]
        new_data_list.append(temp_list)
    data = new_data_list[:-1]
    
    for i in data :
        student_info = StudentModel(
            first_name = i[1] , 
            last_name = i[2] ,
            age = i[3] ,
            branch = i[4] 
        )
        studnet_info.save()
    

    These all are within the "Creating Database model" folder.

    This will do all the work you require. Make sure to debug and understand before committing to database.