首页 > 编程语言 >Python3项目初始化7--ORM及其项目修改

Python3项目初始化7--ORM及其项目修改

时间:2022-08-18 22:57:35浏览次数:50  
标签:return name get -- request ORM user Python3 User

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

标签:return,name,get,--,request,ORM,user,Python3,User
From: https://www.cnblogs.com/sunnyyangwang/p/16600407.html

相关文章

  • Detectron2使用
    Detectron2使用Detectron2安装gitclonehttps://github.com/facebookresearch/detectron2.gitcddetectron2pythonsetup.pybuilddevelop......
  • 函数的递归
    2.函数的递归的定义函数的递归调用:是函数嵌套调用的一种特殊形式具体是指:在调用一个函数的过程中又直接或者间接的调用到本身,是一个死循环,最大递归是1000次,超出之后报错......
  • 23届秋招美团内推推推!开始啦!!
    自我介绍本人为20届应届生,在19年秋招期间,拿到了网易、小米、美团等企业的Offer,最后和美团双向奔赴,在美团工作的这两年,可以说是收获满满,推荐大家来到美团这个温暖的......
  • go 接口 实现sort排序接口 进行自定义排序
    packagemainimport("fmt""math/rand""sort")//学生结构体typeStudentstruct{NamestringIdstringAgeint}typeStudentA......
  • 我写的蓝宝石留言本php版 v4.5
    蓝宝石留言本php版v4.5采用原生php编写,在php5.6~php7.x下调试通过。本留言本使用了utf-8编码。include/config1.php是数据库连接参数的配置文件,include/config2是留言板......
  • iis7 部署网站 各种错误问题
    403-禁止访问:访问被拒绝。您无权使用所提供的凭据查看此目录或页面。这是环境没有安装完全,执行一下以下命令:C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet......
  • 不要高估自己要踏实,写给自己
    我发现有很多很多的人是高估自己的。最典型的就是相亲市场,为什么现在结婚率如此低,有个重要的因素就是,对自己没有一个正确的认识。自己爱的人都是自己配不上的,而能和你结婚......
  • 【PostgreSQL】连接到PostgreSQL Server
    连接pg需要指定以下的参数:·主机地址·端口·数据库名·用户·密码 如果没有指定上面的参数的话,pg会从环境变量中寻找以下的变量值:·PGHOST或PGHOSTADDR·PG......
  • Python 虚拟环境管理神器:virtualenvwrapper-win for windows
    项目开发时,为了不污染全局环境,通常会使用虚拟环境隔离工具:virtualenvvirtualenvwrapper 是将所有的虚拟环境放在同一个目录下,方便管理,在使用shell配合小型开发工具就会......
  • 响应字符数据
        setContentType是为了防止乱码   文件的读取     ......