Django ORM 实现数据的单表 增删改查
一、配置环境
1 Django 连接数据库(MySQL)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'xyz',
'USER':'root',
'PASSWORD':'root',
'HOST':'IP地址',
'PORT':3306,
'CHARSET':'utf8'
}
}
2 Django 默认用的是 mysqldb 改为用 pymysql 连接
import pymysql
pymysql.install_as_MySQLdb()
3 安装 pymysql
pip3 install pymysql
4 定义 models
from django.db import models
# Create your models here.
class User(models.Model):
# id int primary_key auto_increment
id = models.AutoField(primary_key=True, verbose_name='主键')
# username varchar(32)
username = models.CharField(max_length=32, verbose_name='用户名')
password = models.CharField(max_length=64, verbose_name='密码')
5 执行迁移,同步。顺序执行下面个代码(每次修改表都要顺序执行一遍)
python manage.py makemigrations
python manage.py migrate
6 定义 url
from django.contrib import admin
from django.urls import path
from app import views
urlpatterns = [
path('admin/', admin.site.urls),
# 注册功能
path('register/',views.reg),
# 展示用户列表
path('userlist/',views.userlist),
# 编辑用户
path('edit_user/',views.edit_user),
# 删除用户
path('delete_user/',views.delete_user)
]
二、增加
新建 templates\register.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<h1 class="text-center">注册</h1>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form action="" method="post">
<p>username:<input type="text" name="username" class="form-control"></p>
<p>password:<input type="password" name="password" class="form-control"></p>
<input type="submit" class="btn btn-danger btn-block">
</form>
</div>
</div>
</div>
</body>
</html>
获取用户数据,并存入数据库
from django.shortcuts import HttpResponse, render, redirect
from app import models
def register(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
# 第一种增加
# res = models.User.objects.create(username=username, password=password)
# 返回值就是当前被创建的对象本身
# print(res,res.username, res.password)
# 第二种增加
user_obj = models.User(username = username, password = password)
# 保存数据
user_obj.save()
# 先给用户返回一个注册页面
return render(request, 'register.html')
三、查询
def userlist(request):
# 查询出用户表里面所有的数据
# 方式1
# filter括号内可以携带多个参数 参数与参数之间默认是and关系。可以把filter 想成where
# data = models.User.objects.filter()
# print(data)
# 方式2
user = models.User.objects.all()
# return render(request,'userlist.html', {'user_queryset':user_queryset})
return render(request, 'userlist.html', locals())
新建 templates\userlist.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<h1 class="text-center">数据展示</h1>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>ID</th>
<th>username</th>
<th>password</th>
<th>action</th>
</tr>
</thead>
<tbody>
{% for user_obj in user %}
<tr>
<td>{{ user_obj.id }}</td>
<td>{{ user_obj.username }}</td>
<td>{{ user_obj.password }}</td>
<td>
<a href="/edit_user/?user_id={{ user_obj.id }}" class="btn btn-primary btn-xs">编辑</a>
<a href="/delete_user/?user_id={{ user_obj.id }}" class="btn btn-danger btn-xs">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
四、修改
def edit_user(request):
# 获取url问号后面的参数
edit_id = request.GET.get('user_id')
# 查询当前用户想要编辑的数据对象
edit_obj = models.User.objects.filter(id = edit_id).first()
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
# 去数据库中修改对应的数据内容
# 修改数据方式1
# models.User.objects.filter(id=edit_id).update(username=username,password=password)
"""
将filter查询出来的列表中所有的对象全部更新 批量更新操作
只修改被修改的字段
"""
# 修改数据方式2
edit_obj.username = username
edit_obj.password = password
edit_obj.save()
"""
上述方法当字段特别多的时候效率会非常的低
从头到尾将数据的所有字段全部更新一边 无论该字段是否被修改
"""
# 跳转到数据的展示页面
return redirect('/userlist/')
# 将数据对象展示到页面上
return render(request, 'edit_user.html', locals())
新建 templates\edit_user.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<h1 class="text-center">编辑</h1>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form action="" method="post">
<p>username:<input type="text" name="username" class="form-control" value="{{ edit_obj.username }}"></p>
<p>password:<input type="text" name="password" class="form-control" value="{{ edit_obj.password }}"></p>
<input type="submit" class="btn btn-info btn-block" value="编辑">
</form>
</div>
</div>
</div>
</body>
</html>
五、删除
def delete_user(request):
# 获取用户要删除的数据 id值
delete_id = request.GET.get('user_id')
# 直接去数据库中找到对应的数据删除即可
models.User.objects.filter(id = delete_id).delete()
# 跳转到展示页面
return redirect('/userlist/')