在py3.*中利用django使用mysql时,会出现一些问题。由于django默认的是 MySQLdb,但MySQLdb目前不支持py3.*所以我们要改用pymysql,首先要安装pymysql,命令如下:
pip3 install pymysql
然后我们去项目同名的文件夹下找到setting.py中修改:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "dbname",
"USER":"dbusername",
"PASSWORD":"dbpassword",
"HOST":"127.0.0.1",
"PORT":"",
}
}
最后 去项目同名的文件夹下找到 __init__.py文件并在其中添加如下代码:
import pymysql
pymysql.install_as_MySQLdb()
然后执行:
python manage.py makemigrations python manage.py migrate
做一个小的测试:
创建一个app
python manage.py startapp app02
由于想让app2管理app2下面所有的链接地址,而不是通过项目同名下的文件中的urls.py来管理那么我们需要这么做
项目同名文件夹中的urls.py
from django.contrib import admin
from django.urls import path,re_path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("cmdb/",include("app02.urls")),
]
重点是path("cmdb/",include("app02.urls")) 然后我们在app02下创建一个urls.py
"""study_django01 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path
from app02 import views
urlpatterns = [
path("orm/",views.orm),
]
然后再app002下的models.py中编写如下代码
from django.db import models # Create your models here. # 必须继承models.Model class UserInfo(models.Model):
# id列 自增 主键 系统默认会创建这样的玩意儿
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
在命令行执行
python manage.py makemigrations python manage.py migrate
去数据库中查看对应的数据库,可以看到系统为您生成了app02_userinfo表,并且字段就是你填写的两个字段,需要注意的是,系统将会为你自动生成Id字段,并且是自增、主键。
最后在app002下的view.py中编写如下代码
from django.shortcuts import render,HttpResponse # Create your views here.
from app02 import models def orm(request):
# 增*********************
# 创建数据方式一 (推荐)
# models.UserInfo.objects.create( username="root", password="123456") # 创建数据方式二
# obj = models.UserInfo(username="root",password="123456")
# obj.save() # 创建数据方式三
# dic = {"username":"eric","password":"6666"}
# models.UserInfo.objects.create(**dic) # 查**********************
# 查所有
result = models.UserInfo.objects.all()
print(result)
for row in result:
print(row.id,row.username,row.password) # 按条件查
result1 = models.UserInfo.objects.filter(username="root",password="")
print(result1) # 删除
# 全部删除
# models.UserInfo.objects.all().delete() # 按条件删除
models.UserInfo.objects.filter(id=4).delete() # 更新
# 全部更新
models.UserInfo.objects.all().update(password=666)
# 指定更新
models.UserInfo.objects.filter(id=3).update(password=111) return HttpResponse("orm")