简体   繁体   English

使用 django 在前端显示来自 sql 数据库的数据

[英]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.对于从数据库中获取数据,我通常看到人们在models.py中创建一个类并迁移它,然后他们从数据库中获取数据并显示在前端。 my question is, i already have a database which has student_info table and has lots of data.我的问题是,我已经有一个包含student_info表和大量数据的数据库。 I don't want to define student_info class in models.py and do migration.我不想在models.py中定义student_info类并进行迁移。 Instead, since i already have student_info data in sql database .相反,因为我已经在sql database中有student_info数据。 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;我知道的一种方法是直接在views.py中连接sql server;

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

and fetching the data and passing it as variable in index.html .并获取数据并将其作为variable传递给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.但问题是,它只获取一次数据,如果我刷新本地服务器运行的页面,所有内容都会消失,服务器会报告Broken pipe from ('127.0.0.1', 59579)并查看数据,我再次需要重新启动服务器。

Kindly looking for a better approach to show data on front-end from the existing databases请寻找一种更好的方法来显示现有数据库中的前端数据

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.创建一个 StudentData(models.Model) 类,它将您的数据作为模型对象存储在其中,并根据数据定义模型中的所有属性/列,这些属性/列位于 student_info 表中。

Write a simple script ( using pymysql ) to retrive all the data from the student_table , store it in text file .编写一个简单的脚本(使用 pymysql)从 student_table 中检索所有数据,并将其存储在文本文件中。 ( 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 .获取该文本文件,现在在您的 django 项目中,运行 shell 命令或创建新脚本以将 text_file 学生数据传输到模型对象并保存它们。 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.更新:我已经为这个脚本使用了 pymysql,我认为 mysqlconnector 也可以完成这项工作。

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" first_file:“数据检索.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 .然后我正在创建一个文件 text_data.txt ,其中将包含表格的文本数据。 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我的学生表架构有五个字段: id 、 first_name 、 last_name 、 age 、 branch

so my models.py according to this database is here .所以根据这个数据库我的models.py就在这里。 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"第二个文件:“models.py 中的数据输入”

This file takes data and then saves it to the model .该文件获取数据,然后将其保存到模型中。 And you get your database in django .你在 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.确保在提交到数据库之前进行调试和理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM