22、Django ORM介绍
配置数据库引擎, setting操作。
##CREATE DATABASE cmdb_user DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'cmdb_user',
'USER': 'wang',
'PASSWORD': 'Test@123',
'HOST': '192.168.1.118',
'PORT': '3306',
'CHARSET': 'utf6mb4',
}
}
编写models代码
#enconding: utf-8
from django.db import models
class User(models.Model):
name = models.CharField(max_length=32, null=False, default='')
password = models.CharField(max_length=512, null=False, default='')
age = models.IntegerField(null=False, default=0) # age int not null default 0
tel = models.CharField(max_length=32, null=False, default='')
sex = models.BooleanField(null=False, default=True)
create_time = models.DateTimeField(null=False)
生成数据库描述文件
F:\py3proj\07\cmdb>python manage.py makemigrations
Migrations for 'user':
user\migrations\0001_initial.py
F:\py3proj\07\cmdb>python manage.py sqlmigrate user 0001
同步数据库结构
F:\py3proj\07\cmdb>python manage.py migrate
mysql> use cmdb_user;
mysql> desc user_user;
打开Python命令
F:\py3proj\07\cmdb>python manage.py shell
>>> from user.models import User
>>> user = User()
>>> user.name = 'kk'
>>> user.password = '123456'
>>> user.age = 20
>>> user.sex = 1
>>> user.tel = '123456'
>>> user.addr = 'beijing'
>>> from datetime import datetime
>>> user.create_time = datetime.now()
>>> user.save()
>>> u = User(name='kk1', password='123456',create_time = datetime.now())
>>> u.save()
mysql> select * from user_user; # 数据库查看,创建了2条记录。
>>> u.age = 33 #更新这条记录属性
>>> u.save()
>>> u.delete() #删除这条记录
>>> User.objects.all()
>>> user = User.objects.all() # 获取所有用户对象
>>> user[0]
>>> user[0].id
>>> user[0].name
>>> user[0].delete()
插入数据
mysql> INSERT INTO `user_user` (`name`, `password`, `age`, `tel`, `sex`, `create_time`, `addr`) VALUES ('kk3', '123456', 33, '', 1, now(), '');
mysql> INSERT INTO `user_user` (`name`, `password`, `age`, `tel`, `sex`, `create_time`, `addr`) VALUES ('kk4', '123456', 0, '', 1, now(), '');
继续学习orm操作
创建多个用户
>>> from user.models import User
>>> User.objects.count() # 查语句条数。
>>> from datetime import datetime
>>> for i in range(10):
... u = User()
... u.create_time = datetime.now()
... u.name = 'kk_{0}'.format(i)
... u.save()
>>> User.objects.filter(name='kk_1')
>>> User.objects.filter(age__gte=10) 大于等于
>>> User.objects.filter(age__lte=10) 小于
>>> User.objects.filter(name__contains='kk') 包含
>>> User.objects.exclude(name__contains='kk_') 剔除满足条件的
>>> User.objects.filter(age__lt=10, name__endswith='4') # age>10 and name like '%4'
>>> User.objects.filter(age__lte=10).update(age=20,addr="北京") # 更新
>>> User.objects.filter(age__gt=10).delete # 批量删除
23、项目修改
调整model,
#enconding: utf-8
from django.db import models
class User(models.Model):
name = models.CharField(max_length=32, null=False, default='') # => name varchar(32) not null default ''
password = models.CharField(max_length=512, null=False, default='')
age = models.IntegerField(null=False, default=0) # => age int not null default 0
tel = models.CharField(max_length=32, null=False, default='')
sex = models.BooleanField(null=False, default=True)
create_time = models.DateTimeField(null=False)
addr = models.CharField(max_length=120, null=False, default='')
@classmethod
def delete_by_id(cls, id):
return cls.objects.filter(id=id).delete()
def as_dict(self):
return {
'id': self.id,
'name': self.name,
'age': self.age,
'tel': self.tel,
'sex': self.sex,
'password': self.password
}
调整视图view.py
#enconding: utf-8
from django.shortcuts import render, redirect
from .models import User
from .validators import UserValidator
def index(request):
if not request.session.get('user'):
return redirect('user:login')
return render(request, 'user/index.html', {'users': User.objects.all()})
def login(request):
if 'GET' == request.method:
return render(request, 'user/login.html')
else:
name = request.POST.get('name')
password = request.POST.get('password')
user = UserValidator.valid_login(name, password)
if user:
request.session['user'] = user.as_dict()
return redirect('user:index')
else:
return render(request, 'user/login.html', {
'name': name,
'errors': {'default': '用户名或密码错误.'}
})
def logout(request):
request.session.flush() # 清除单个用户, clear清除所有用户session
return redirect('user:login')
def delete(request):
if not request.session.get('user'):
return redirect('user:login')
uid = request.GET.get('uid', '')
if uid.isdigit():
# delete_user(uid)
User.delete_by_id(uid)
return redirect('user:index')
def view(request):
if not request.session.get('user'):
return redirect('user:login')
uid = request.GET.get('uid', '')
return render(request, 'user/view.html', {'user': User.objects.get(pk=uid)})
def update(request):
if not request.session.get('user'):
return redirect('user:login')
is_valid, user, errors = UserValidator.valid_update(request.POST)
if is_valid:
user.save()
return redirect('user:index')
else:
return render(request, 'user/view.html',
{'user': user, 'errors': errors})
def create(request):
if not request.session.get('user'):
return redirect('user:login')
if 'GET' == request.method:
return render(request, 'user/create.html')
else:
is_valid, user, errors = UserValidator.valid_create(request.POST)
if is_valid:
user.save()
return redirect('user:index')
else:
return render(request, 'user/create.html', {
'user': user,
'errors': errors,
})
补充用户validators.py类。
# encoding: utf-8
from django.utils import timezone
from .models import User
class Validator(object):
@classmethod
def is_integer(cls, value):
try:
int(value)
return True
except BaseException as e:
return False
class UserValidator(Validator):
@classmethod
def valid_login(cls, name, password):
user = None
try:
user = User.objects.get(name=name)
except BaseException as e:
pass
if user is None:
return None
if user.password == password:
return user
return None
@classmethod
def valid_name_unique(cls, name, id=None):
user = None
try:
user = User.objects.get(name=name)
except BaseException as e:
pass
if user is None:
return True
else:
return str(user.id) == str(id)
@classmethod
def valid_update(cls, params):
is_valid = True
user = None
errors = {}
# print(User.objects.get(pk=params.get('id', '').strip()))
try:
user = User.objects.get(pk=params.get('id', '').strip())
except BaseException as e:
errors['id'] = '用户信息不存在'
is_valid = False
return is_valid, user, errors
name = params.get('name', '').strip()
if name == '':
errors['name'] = '用户名不能为空'
is_valid = False
elif not cls.valid_name_unique(name, user.id):
errors['name'] = '用户名已存在'
is_valid = False
else:
user.name = name
age = params.get('age', '0').strip()
if not cls.is_integer(age):
errors['age'] = '年龄格式错误'
is_valid = False
else:
user.age = int(age)
user.tel = params.get('tel', '')
user.sex = int(params.get('sex', '0'))
return is_valid, user, errors
@classmethod
def valid_create(cls, params):
is_valid = True
user = User()
errors = {}
user.name = params.get('name', '').strip()
if user.name == '':
is_valid = False
errors['name'] = '用户名不能为空'
else:
try:
User.objects.get(user.name)
is_valid = False
errors['name'] = '用户名重复'
except BaseException as e:
pass
user.age = params.get('age', '0').strip()
if not user.age.isdigit():
errors['age'] = '年龄格式错误'
is_valid = False
user.tel = params.get('tel', '')
user.sex = int(params.get('sex', '0'))
user.password = params.get('password', '').strip()
if user.password == '' or params.get('other_password') != user.password:
is_valid = False
errors['password'] = '密码不能为空, 且两次输入密码必须相同'
user.create_time = timezone.now()
return is_valid, user, errors
验证ok,备份cmdb08-18gaizao.rar。
ORM文档链接:https://yiyibooks.cn/xx/Django_1.11.6/index.html