1、安装django库
pip install Django
2、自动生成项目
django-admin startproject HelloWorld
3、启动项目
python manage.py runserver 0.0.0.0:8000
4、生成模块
django-admin startapp TestModel
5、配置连接多个MySQL数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'zwfw': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'zwfw', # 数据库名称
'HOST': '192.168.1.6', # 数据库地址,本机 ip 地址 127.0.0.1
'PORT': 3306, # 端口
'USER': 'root_DB', # 数据库用户名
'PASSWORD': 'password', # 数据库密码
},
'linyi': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'linyi', # 数据库名称
'HOST': '192.168.1.6', # 数据库地址,本机 ip 地址 127.0.0.1
'PORT': 3306, # 端口
'USER': 'root_DB', # 数据库用户名
'PASSWORD': 'password', # 数据库密码
},
}
修改mysql对应配置路由
# 配置数据库操作路由
DATABASE_ROUTERS = ['pyetl1.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
'wuliu': 'zwfw',
'ying': 'lin',
'sdi': 'sd_lii',
}
生成指定MySQL模型models文件
python manage.py inspectdb --database=linyi > yingxiao/models.py
简单的MySQL操作
from django.http import HttpResponse
from wuliu.models import RegionManage
数据库操作
def testdb(request):
test1 = RegionManage(row_id=1)
test1.save()
return HttpResponse("
数据添加成功!
")查询全部数据
def getdataall(request):
# 初始化
response = ""
response1 = ""
listTest = RegionManage.objects.all()
# filter相当于SQL中的WHERE,可设置条件过滤结果
# response2 = RegionManage.objects.filter(id=1)
# 获取单个对象
# response3 = RegionManage.objects.get(id=1)
# 限制返回的数据 相当于 SQL 中的 OFFSET 0 LIMIT 2;
# RegionManage.objects.order_by('name')[0:2]
# 数据排序
# RegionManage.objects.order_by("id")
# 上面的方法可以连锁使用
# RegionManage.objects.filter(name="runoob").order_by("id")
# 输出所有数据
for var in listTest:
response1 += var.operateusername
response = response1
return HttpResponse("<p>" + response + "</p>")
更新数据
def updatedatabyid(request):
# 修改其中一个id=1的name字段,再save,相当于SQL中的UPDATE
test1 = RegionManage.objects.get(row_id=1)
test1.operateusername = '测试组织机构'
test1.save()
# 另外一种方式
# Test.objects.filter(id=1).update(name='Google')
# 修改所有的列
# Test.objects.all().update(name='Google')
return HttpResponse("<p>修改成功</p>")
删除数据
def deldata(request):
# 删除id=1的数据
test1 = RegionManage.objects.get(row_id=1)
test1.delete()
# 另外一种方式
# Test.objects.filter(id=1).delete()
# 删除所有数据
# Test.objects.all().delete()
return HttpResponse("<p>删除成功</p>")
以下是学习过程中遇到的问题
1、启动的时候报错
You have 18 unapplied migration(s). Your project may not work properly until you apply
将服务关闭后执行以下代码,然后启动就正常了
python manage.py migrate
2、MySQL版本问题
Traceback (most recent call last):
File "manage.py", line 22, in
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "D:\software\anaconda\envs\data\lib\site-packages\django\core\management__init.py", line 442, in execute_from_command_line
utility.execute()
File "D:\software\anaconda\envs\data\lib\site-packages\django\core\management\init__.py", line 436, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\software\anaconda\envs\data\lib\site-packages\django\core\management\base.py", line 412, in run_from_argv
self.execute(args, **cmd_options)
File "D:\software\anaconda\envs\data\lib\site-packages\django\core\management\base.py", line 458, in execute
output = self.handle(args, options)
File "D:\software\anaconda\envs\data\lib\site-packages\django\core\management\commands\inspectdb.py", line 46, in handle
for line in self.handle_inspection(options):
File "D:\software\anaconda\envs\data\lib\site-packages\django\core\management\commands\inspectdb.py", line 62, in handle_inspection
with connection.cursor() as cursor:
File "D:\software\anaconda\envs\data\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, kwargs)
File "D:\software\anaconda\envs\data\lib\site-packages\django\db\backends\base\base.py", line 330, in cursor
return self._cursor()
File "D:\software\anaconda\envs\data\lib\site-packages\django\db\backends\base\base.py", line 306, in _cursor
self.ensure_connection()
File "D:\software\anaconda\envs\data\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(args, **kwargs)
File "D:\software\anaconda\envs\data\lib\site-packages\django\db\backends\base\base.py", line 289, in ensure_connection
self.connect()
File "D:\software\anaconda\envs\data\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(args, **kwargs)
File "D:\software\anaconda\envs\data\lib\site-packages\django\db\backends\base\base.py", line 272, in connect
self.init_connection_state()
File "D:\software\anaconda\envs\data\lib\site-packages\django\db\backends\mysql\base.py", line 257, in init_connection_state
super().init_connection_state()
File "D:\software\anaconda\envs\data\lib\site-packages\django\db\backends\base\base.py", line 239, in init_connection_state
self.check_database_version_supported()
File "D:\software\anaconda\envs\data\lib\site-packages\django\db\backends\base\base.py", line 214, in check_database_version_supported
raise NotSupportedError(
django.db.utils.NotSupportedError: MySQL 8 or later is required (found 5.7.43).
找到下面文件,找到对应行,注释掉以后就正常了。
\Lib\site-packages\django\db\backends\base\base.py
搜索下面方法
注释掉代码
check_database_version_supported()
3、生成models运行查询代码报错,id缺少key配置。
yingxiao.TAjxzsCxlatzs: (models.E004) 'id' can only be used as a field name if the field also sets 'primary_key=True'.
找到对应yingxiao.TAjxzsCxlatzs:类,在id后添加 primary_key=True