初学Django遇到的数据库相关问题总结

以下是我初学Django,用mssql适配器和与数据库交互遇到的问题和注意事项,基本上搜索都能出来,总结记录了一下。

我用的适配器是django-mssql,其他的如pyodbc也还可以,感觉配置比django-mssql简单,但也没有相差很多,酌情选择

安装pywin32模块时,找不到python路径

错误显示为Python version 2.7 required, which was not found in the registry

  • 新建register.py文件,将以下代码复制:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# script to register Python 2.0 or later for use with win32all
# and other extensions that require Python registry settings
#
# written by Joakim Loew for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm
#
# modified by Valentine Gogichashvili as described in http://www.mail-archive.com/distutils-sig@python.org/msg10512.html

import sys

from _winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
installpath, installpath, installpath
)

def RegisterPy():
try:
reg = OpenKey(HKEY_CURRENT_USER, regpath)
except EnvironmentError as e:
try:
reg = CreateKey(HKEY_CURRENT_USER, regpath)
SetValue(reg, installkey, REG_SZ, installpath)
SetValue(reg, pythonkey, REG_SZ, pythonpath)
CloseKey(reg)
except:
print "*** Unable to register!"
return
print "--- Python", version, "is now registered!"
return
if (QueryValue(reg, installkey) == installpath and
QueryValue(reg, pythonkey) == pythonpath):
CloseKey(reg)
print "=== Python", version, "is already registered!"
return
CloseKey(reg)
print "*** Unable to register!"
print "*** You probably have another Python installation!"

if __name__ == "__main__":
RegisterPy()`

django-mssql安装注意事项

  • 执行python setup.py install命令
  • 将python的安装目录下的django的同目录下的django_mssql-xxb1-py2.7.egg中sqlserver_ado目录拷贝到\Python27\Lib\site-packages\django\db\backends目录下

settings.py中DATABASES的ENGINE配置

从数据库中自动生成django模型

  • 通过python manage.py inspectdb >…/models.py命令自动生成模型。
  • reference

不使用django的orm,如何写原生sql并且返回字典

有时候要做一些复杂查询,orm可能不能满足,还是写原生sql方便一些。

两种方法:

  • Manager.raw(),个人觉得不好,不多说
  • 避免数据模型,自定义sql语句

以下说的是第二种方法

  • 概览:
    from django.db import connection,transaction:导入模块
    django.db.connection:代表默认的数据库连接
    django.db.transaction:代表默认数据库事务(transaction)
    connection.cursor(): 获得一个游标(cursor)对象
    cursor.execute(sql, [params]):执行SQL
    cursor.fetchone() 或者 cursor.fetchall():返回结果行
  • 实例(我常用):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from django.db import connection,transaction
import json
def function(request,id):
cursor = connection.cursor()
if request.method == 'GET':
cursor.execute("select * from table where id ='%s'"%id)

# fetchall返回所有结果,fetchone返回第一个结果,数据形式:fetchone-->() fetchall-->[()]
raws = cursor.fetchall()

# 获得表的属性list
# cursor.description中记录了表的很多信息,每个元素都是表一列的信息(对应代码中的desc),desc本身又是个tuple,desc[0]记录的就是该列的属性名,详情可print看看
col_names = [desc[0] for desc in cursor.description]

# zip()函数将两参数的值一一对应产生tuple,并用dict()函数转成字典
res_list = [dict(zip(col_names, raw)) for raw in raws]

# 转成json返回给前台,注意编码问题
return HttpResponse(json.dumps(user_list,encoding='GB2312'),content_type="application/json")

执行增删改操作,则在cursor.execute()之后调用transaction.commit_unless_managed()来保证你的更改提交到数据库。

印象中django-mssql和pywin32的版本问题也挺头疼,资源挺难找的,但时间太久了,记错勿怪