For the solution, you could do something simple.
Create a StudentData(models.Model) class that will store your data as model objects in them and define all the attributes/columns in models based on the data in the student info table.
Create a simple script (using pymysql) to retrieve all of the data from the student table and save it to a text file.
Take that text file and run a shell command or write a new script in your Django project to transfer the text file student data to model objects and save them. You now have your data.
This should work fine, in my opinion. If you want code as well. I’ll incorporate it.
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()
I used pymysql for these scripts, but I believe mysqlconnector will also work.
Make a folder called “Creating Database Model” within your project.
To connect, enter your password. I’m using a college database with a student table containing some student data. Then I’m going to make a file called text data.txt that will contain the table’s text data. I used string formatting for convenience and better data retrieval on the other side.
So, according to this database, my models.py is here. You design your own based on your requirements.
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()
All of these are in the “Creating Database Model” folder. Read this article on views in SQL from scaler topics for more information or clarification. Also, this can be valid solution, but maybe try first the Django legacy database integration.
This will complete all of your tasks. Before committing to the database, make sure to debug and understand.