环境
Python 3.10.0
django 4.0.6
需求
需要将Django默认的sqlite3数据变为postgresql数据库
操作
- 在settings.py文件中找到DATABASES配置项
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
- 默认配置,注释掉sqlite3
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
}
}
- 添加postgresql配置
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres', #需要连接的数据库名字
'USER': 'postgres', #用户名
"PASSWORD" : '*******', #自己的密码
"HOST":'10.19.*.*',
'PORT':5432
}
}
- 测试是否连接成功
# postgresql数据库
# Django自带,若没有需安装:pip install psycopg2
import psycopg2
# 连接postgresql数据库
def postgresql(request):
conn = psycopg2.connect(database="postgres", user="postgres", password="******", host="10.19.*.*", port="5432")
print(conn)
# 调用游标对象
cur = conn.cursor()
# 查询
cur.execute("SELECT * from tab_test")
rows = cur.fetchall()
for row in rows:
print("row0 =", row[0])
print("row1 =", row[1])
# # 提交更改,增添或者修改数据只会必须要提交才能生效
# conn.commit()
conn.close()
return HttpResponse('')