转载自:bobo0609
ORM 即 关系对象映射 ( Object Relational Mapping)
创建类 app01/models.py
from django.db import models
class UserInfo(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
]
修改数据库引擎 settings.py DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'dbname',
'USER': 'root',
'PASSWORD': 'xxx',
'HOST': '',
'PORT': '',
}
}
# 如果在model.py中修改了类,重新执行以上命令
from django.db import models
class UserInfo(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
email = models.CharField(max_length=60,null=True) # 增加列时不允许为空,需添加null=True,否则报错
根据类自动创建数据库表 -- models.py
字段类型
字符串类型validators -> django form 自定义错误信息(欠)
from django.db import models
# Create your models here.
class UserInfo(models.Model):
# 生成的表名称为app01_userinfo
# 会自动创建id列(自增,主键)
username = models.CharField(max_length=32,blank=True,verbose_name='用户名') # 用户名列,字符串类型,指定长度
password = models.CharField(max_length=60, help_text='pwd')
email = models.EmailField(max_length=19,null=True,error_messages={'invalid': '请输入邮箱'}
caption = models.CharField(max_length=32,unique=True)
user_type_choices = ((1, '超级用户'), (2, '普通用户'),(3, '临时用户'),) # 保存在内存中
user_type_id = models.IntegerField(choices=user_type_choices,default=1)
ctime = models.DateTimeField(auto_now_add=True, null=True)
mtime = models.DateTimeField(auto_now=True, null=True)
'''
方式一: mtime 时间不会更新
obj=UserInfo.objects.filter(id=1).update(caption='CEO')
方式二: mtime 时间会更新
obj=UserInfo.objects.filter(id=1).first()
obj.caption = 'CEO'
obj.save()
'''
from app01 import models
def orm(request):
# 增
models.UserInfo.objects.create(username='root',password='123')
dic = {'username': 'xxx', 'password': '666'}
models.UserInfo.objects.create(**dic)
obj = models.UserInfo(username='alex',password='123')
obj.save()
# 查
result = models.UserInfo.objects.all()
result = models.UserInfo.objects.filter(username='root',password='123')
print(result) #结果为Django的QuerySet类型 ,,]>
for row in result:
print(row.id,row.username,row.password)
dic = {'name': 'xxx', 'age_gt': '19'}
models.User.objects.filter(**dic)
# 删
models.UserInfo.objects.filter(id=4).delete()
# 改
models.UserInfo.objects.filter(id=3).update(password="69")
外键约束 .
ForeignKey("PrimaryTable",to_filed='xxx')
from django.db import models
# Create your models here.
class UserGroup(model s.Model):
uid = models.AutoField(primary_key=True) #自定义自增列,必须声明primary_key=True
caption = models.CharField(max_length=32,unique=True)
class UserInfo(models.Model):
username = models.CharField(max_length=32,blank=True,verbose_name='用户名')
password = models.CharField(max_length=60, help_text='pwd')
email = models.CharField(max_length=60)
user_group = models.ForeignKey("UserGroup",to_field='uid',default=1)
# default=1 表示默认属于哪个部门,django在数据库中将user_group存取字段为user_group_id,实际上user_group为UserGroup的对象封装了(uid,caption,ctime,uptime)
from app01 import models
def orm(request):
models.UserInfo.objects.create(
username='root1',
password='123',
email="[email protected]",
user_group = models.UserGroup.objects.filter(id=1).first() # 或 user_group_id = 1 (推荐)
)
user_list = Userinfo.objects.all()
for row in user_list:
print(row.user_group) #这里 user_group代指 UserGroup 对象
print(row.user_group.id) # 等同于 print(row.user_group_uid)
print(row.user_group.caption)
urls.py
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^login/', views.login),
url(r'^index/', views.index),
url(r'^user_info/', views.user_info),
url(r'^userdetail-(?P\d+)/', views.user_detail),
url(r'^userdel-(?P\d+)/', views.user_del),
url(r'^useredit-(?P\d+)/', views.user_edit),
]
from django.shortcuts import render,HttpResponse,redirect
def login(request):
models.UserGroup.objects.create(caption='DBA')
if request.method == "GET":
return render(request, 'login.html')
elif request.method == "POST":
# 数据库中执行 select * from user where usernam='x' and password='x'
u = request.POST.get('user')
p = request.POST.get('pwd')
# count = models.UserInfo.objects.filter(username=u, password=p).count()
obj = models.UserInfo.objects.filter(username=u, password=p).first()
if obj:
return redirect('/cmdb/index/')
else:
return render(request, 'login.html')
else:
# PUT,DELETE,HEAD,OPTION...
return redirect('/index/')
def index(request):
return render(request, 'index.html')
def user_info(request):
if request.method == "GET":
user_list = models.UserInfo.objects.all() # print(user_list.query)
group_list = models.UserGroup.objects.all()
return render(request, 'user_info.html', {'user_list': user_list, "group_list": group_list})
elif request.method == 'POST':
u = request.POST.get('user')
p = request.POST.get('pwd')
models.UserInfo.objects.create(username=u,password=p)
return redirect('/cmdb/user_info/')
def user_detail(request, nid):
obj = models.UserInfo.objects.filter(id=nid).first()
# models.UserInfo.objects.get(id=nid) # 取单条数据,但如果不存在则报错
return render(request, 'user_detail.html', {'obj': obj})
def user_del(request, nid):
models.UserInfo.objects.filter(id=nid).delete()
return redirect('/cmdb/user_info/')
def user_edit(request, nid):
if request.method == "GET":
obj = models.UserInfo.objects.filter(id=nid).first()
return render(request, 'user_edit.html',{'obj': obj})
elif request.method == "POST":
nid = request.POST.get('id')
u = request.POST.get('username')
p = request.POST.get('password')
models.UserInfo.objects.filter(id=nid).update(username=u,password=p)
return redirect('/cmdb/user_info/')
Title
Deployment
Title
Deployment
添加用户
用户列表
{% for row in user_list %}
-
{{ row.username }}
{{ row.user_group.caption }}
删除 |
编辑
{% endfor %}
Title
Deployment
Title
Deployment