Django: Sqlite Transfer Into TimescaleDB Application
安装timescaledb(win10)
安装PostgreSQL
下载:(下载地址)https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
检验:打开系统服务面板,可查询pg服务
安装TimescaleDB
-
下载:(下载地址)https://docs.timescale.com/latest/getting-started/installation/windows/installation-windows
-
解压,并关闭pg service
-
管理员身份运行timescaledb setup
- Select yes
- The setup will ask for the 'postgresql.conf' file. This is the PostgreSQL config file.
PostgreSQL\data
-
系统环境变量添加
PostgreSQL\bin
检查:是否存在
postgresql.conf
-
重新启动pg服务
切换数据库
(1)在setting.py
配置中添加pg数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'new': {
'ENGINE': 'timescale.db.backends.postgresql',
'NAME': 'smart_planning_site',
'USER': '****',
'PASSWORD': '****',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
(2)安装django-timescaledb
包
pip install django-timescaledb
(3)迁移
python manage.py migrate --database=new
(4)清空新库(如果新库存在一些无用数据)
python manage.py flush --database=new
(5)从旧数据库中导出json数据
python manage.py dumpdata>data.json
(6)加载数据至新数据库
python manage.py loaddata data.json --database=new
(7)删除配置文件中原有数据库的信息,并将name置为default
DATABASES = {
'default': {
'ENGINE': 'timescale.db.backends.postgresql',
'NAME': 'smart_planning_site',
'USER': '****',
'PASSWORD': '****',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
TimeScaleDB的使用
-
在需要时间序列分析的表上添加时间字段名称为
time
(或者修改已有的时间字段名称) -
生成迁移文件
python manage.py makemigrations
- 数据迁移
python manage.py migrate
-
将
models.DateField(null=True)
改为time = TimescaleDateTimeField(interval="1 day")
注意:此时若再生成迁移文件会报错,找不到超表函数,具体原因未知
-
添加时序序列数据库的
model manager
timescale = TimescaleManager()
跟时序分析相关的表用此manager查数据,其他仍沿用object
验证脚本
-
运行django服务
-
在
django console
运行以下脚本,检验
# import model package
import *.models as ml
from django.utils import timezone
from datetime import timedelta
ranges = (timezone.now() - timedelta(days=30), timezone.now())
# query 30 days results
ml.Model.timescale.filter(time__range=ranges)
爱生活、爱编程