数据库表的创建:
使用mysql时注意,在setting.py中的设置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', #mysql的引擎
'NAME': '', #数据库名
'USER': '', #数据库用户名
'PASSWORD': '', #数据库密码
'HOST': '127.0.0.1', #数据库host
'PORT': '3306', #数据库端口
},
}
还需在项目文件夹下的__init__.py中添加mysql的驱动:
#django默认使用MySQLdb模块连接mysql
#需要主动修改为pymysql
import pymysql
pymysql.install_as_MySQLdb()
models.py # 在这个文件中创建类
from django.db import models
# 生成的表名为day1_userinfo
class UserInfo(models.Model): #创建的类必须继承models.Model
# id列,自增,主键 不用用户创建 django会自己给你创建一个
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
在命令符界面执行:
python manage.py makemigrations #生成临时文件在migrations文件夹中
python manage.py migrate #在数据库中生成表
生成了django自带的很多张表
数据库表基本操作:
def orm(request):
#插入数据
#方式1:
models.UserInfo.objects.create(username='root',password='123',)
#方式2
obj = models.UserInfo(username='zhangjian', password='123')
obj.save()
#方式3
dic ={'username': 'hapi', 'password': '1123'}
models.UserInfo.objects.create(**dic)
#查询数据
#查询表出来的是一个django表对象是以列表QuerySet对象
# QuerySet对象就相当于是一个列表,如下:
# <QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
result = models.UserInfo.objects.all() #查询所有
result = models.UserInfo.objects.filter(username='root',password='123') #条件查询
for row in result: #对表进行循环取出值
print(row.id, row.username, row.password)
#删除操作
models.UserInfo.objects.filter(username='root').delete() #删除用户名为root的
#更新操作
models.UserInfo.objects.all().update(password=666)#所有用户密码改成666
return HttpResponse('orm')
页面操作数据库增删改查:
url路由配置:
url(r'^index/', views.index),
url(r'^user_info/', views.user_info),
url(r'^userdetail-(?P<uid>d+)/', views.userdetail),
url(r'^userdel-(?P<uid>d+)/', views.userdel),
url(r'^usered-(?P<uid>d+)/', views.usered),
index.html页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style> body{ margin: 0; } .menu{ display: block; padding: 5px; } </style> <body> <div style="height: 48px;background-color: black;color: white"> <h3>111111111111111</h3> </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0; 200px;background-color: brown;"> <a class="menu" href="/user_info/">用户管理</a> <a class="menu" href="/user_group/">用户组管理</a> </div> <div style="position: absolute;top: 48px;left: 210px;bottom: 0;right: 0;overflow: auto;"> </div> </div> </body> </html>
py代码:
def index(request): return render(request, 'index.html')
查询用户页面user_info.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style> body{ margin: 0; } .menu{ display: block; padding: 5px; } </style> <body> <div style="height: 48px;background-color: black;color: white"> <h3>111111111111111</h3> </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0; 200px;background-color: brown;"> <a class="menu" href="/user_info/">用户管理</a> <a class="menu" href="/user_group/">用户组管理</a> </div> <div style="position: absolute;top: 48px;left: 210px;bottom: 0;right: 0;overflow: auto;"> <h3>添加用户</h3> <form action="/user_info/" method='POST'> <input type="text" name="user"/> <input type="text" name="pwd" /> <input type="submit" name="添加"/> </form> <h3>用户列表</h3> <ul> {% for row in user_list %} <li> <a href="/userdetail-{{ row.id }}/">{{ row.username }}</a> | <a href="/userdel-{{ row.id }}/">删除</a> | <a href="/usered-{{ row.id }}/">编辑</a> </li> {% endfor %} </ul> </div> </div> </body> </html>
用户详情页面userdetail.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style> body{ margin: 0; } .menu{ display: block; padding: 5px; } </style> <body> <div style="height: 48px;background-color: black;color: white"> <h3>111111111111111</h3> </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0; 200px;background-color: brown;"> <a class="menu" href="/user_info/">用户管理</a> <a class="menu" href="/user_group/">用户组管理</a> </div> <div style="position: absolute;top: 48px;left: 210px;bottom: 0;right: 0;overflow: auto;"> <h1>用户详细信息</h1> <h5>{{ obj.id }}</h5> <h5>{{ obj.username }}</h5> <h5>{{ obj.password }}</h5> </div> </div> </body> </html>
py代码:
def user_info(request): if request.method == "GET": user_list = models.UserInfo.objects.all() print(user_list.query) #查看原生的sql语句 elif request.method == "POST": u = request.POST.get('user') p = request.POST.get('pwd') models.UserInfo.objects.create(username=u, password=p) return redirect('/user_info/') return render(request, 'userinfo.html', {"user_list": user_list})
def userdetail(request, uid):
obj = models.UserInfo.objects.filter(id=uid).first() #取id=uid的用户
return render(request, 'user_detail.html', {"obj": obj})
删除用户py代码:
def userdel(request, uid): models.UserInfo.objects.filter(id=uid).delete() return redirect('/user_info/')
修改用户py代码:
def usered(request, uid): if request.method == "GET": obj = models.UserInfo.objects.filter(id=uid).first() return render(request, 'usered.html', {"obj": obj}) elif request.method == "POST": u = request.POST.get("username") p = request.POST.get("password") models.UserInfo.objects.filter(id=uid).update(username=u, password=p) return redirect('/user_info/')
业务线和主机列表案列:
model.py
class Host(models.Model): hostname = models.CharField(max_length=32, db_index=True) ip = models.GenericIPAddressField(db_index=True,protocol="ipv4") port = models.IntegerField() b = models.ForeignKey('Business', to_field='id') class Business(models.Model): caption = models.CharField(max_length=32) code = models.CharField(max_length=32, null=True)
views.py
def business(request): v1 = models.Business.objects.all() #取出来的是queryset对象 v2 = models.Business.objects.all().values('id', 'caption') # 取出来的是一个字典方式 如果出现values()都是字典的方式 v3 = models.Business.objects.all().values_list('id', 'caption') # 取出来是一个元组方式 如果出现values()都是元组的方式 return render(request, 'business.html', {'v1': v1, 'v2': v2, 'v3': v3})
business.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>业务线列表(对象)</h1> <ul> {% for row in v1 %} <li>{{ row.id }} - {{ row.caption }} - {{ row.code }}</li> {% endfor %} </ul> <ul> <h1>业务线列表(字典)</h1> {% for row in v2 %} <li>{{ row.id }} - {{ row.caption }}</li> {% endfor %} </ul> <ul> <h1>业务线列表(元组)</h1> {% for row in v3 %} <li>{{ row.0 }} - {{ row.1 }}</li> {% endfor %} </ul> </body> </html>
结果:
urls.py
url(r'^business$', views.business), url(r'^host$', views.host),
views.py
def host(request): v1 = models.Host.objects.filter(id__gt=0) return render(request, 'host.html', {'v1': v1})
host.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>主机信息</h1> <table border="1"> <thead> <tr>
<th>序号</th> <th>主机名</th> <th>IP</th> <th>端口</th> <th>业务线ID</th> <th>业务线名称</th> </tr> </thead> <tbody> {% for row in v1 %} <tr host-id="{{ row.id }}" bid="{{ row.b_id }}"> #可以给tr增加属性 来传主机ID 和 Business表的 b_id {# <td>{{ row.id }}</td>#} #一般不显示主机ID
<td>{{ forloop.counter }}</td> #自动产生序号 还有 forloop.counter0 <td>{{ row.hostname }}</td> <td>{{ row.ip }}</td> <td>{{ row.port }}</td> <td>{{ row.b_id }}</td> #跨表操作Business表的id <td>{{ row.b.caption }}</td> #跨表操作Business表的caption </tr> {% endfor %} </tbody> </table> </body> </html>
结果: