django进阶mysql+echarts
- 首先在setting.py中配置mysql数据库:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'sea',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '',
'PORT': '',
}
}
假如你的数据库中没有表,那么你可以通过models创建,在models.py中:
from django.db import models
class SeaInv(models.Model):
n = models.DecimalField(max_digits=7, decimal_places=4, blank=True, null=True)
e = models.DecimalField(max_digits=7, decimal_places=4, blank=True, null=True)
site = models.CharField(max_length=20, blank=True, null=True)
ptime = models.DateTimeField()
oxy = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True)
ph = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True)
wtem = models.FloatField(blank=True, null=True)
sail = models.FloatField(blank=True, null=True)
no3 = models.FloatField(db_column='NO3', blank=True, null=True) # Field name made lowercase.
co2 = models.FloatField(db_column='CO2', blank=True, null=True) # Field name made lowercase.
hard = models.FloatField(blank=True, null=True)
po3 = models.FloatField(db_column='PO3', blank=True, null=True) # Field name made lowercase.
sio3 = models.FloatField(db_column='SiO3', blank=True, null=True) # Field name made lowercase.
orp = models.FloatField(db_column='ORP', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'sea_inv'
假若你的数据库中有数据,那么你可以通过输入命令python manage.py inspectdb 将数据库中的数据表翻译为django认可的写法:
(sea_data) C:\Users\HP\PycharmProjects\sea_data>python manage.py inspectdb
再通过makemigrations
(sea_data) C:\Users\HP\PycharmProjects\sea_data>python manage.py makemigrations sea_app 把翻译好的数据库放入models.py
再将应用的数据库迁移
(sea_data) C:\Users\HP\PycharmProjects\sea_data>python manage.py migrate
现在开始实现数据可视化:
首先在url.py中编写控制器
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index)
]
根据url,django会自动匹配对应的视图函数index(),此时我们需要在views.py中编写index()的业务逻辑
def index(request):
sea_inv_data = SeaInv.objects.all()
return render(request, 'index.html', locals())
这部分的意思是获取url请求后,index函数会帮我们获取数据库当中的值传给index.html页面。
首先你要在setting中配置好static文件
在setting中添加这个路径:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
在html页面的js代码中引入数据库传来的值
var y = [];
var x = [];
{
% for i in sea_inv_data %}
y.push("{
{ i.co2 }}")
x.push("{
{ i.ptime }}")
{
% endfor %}
再运行服务器,就能实现可视化:
但这个ajax异步传输数据以及与前端交互的一些方法,仍不会使用,以上仅供思路参考,如有不足,欢迎指正!