DJango 学习(6)—— Django 数据库连接以及简单的前后端数据交互
pycharm 链接数据库
"""三个位置右侧上方 database左下方 database配置里面的 plugins 插件搜索重装 pycharmpycharm 可以充当很多数据库的客户端"""
django orm
"""orm: 对象关系映射作用:能够让不会sql 语句的小白也可以通过 python 面向对象的代码简单快捷的操作数据库不足:封装程度太高,有时候 sql 语句的效率偏低 需要自己写 sql 语句表 ------------ 类记录 ------------ 对象某个字段的值 -------- 对象属性应用 models.py 文件"""# 0. setting.py 配置文件修改连接的数据库# 项目指定的数据库DATABASES = {'default': {# 'ENGINE': 'django.db.backends.sqlite3',# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),'ENGINE': "django.db.backends.mysql",'NAME': 'test518',"HOST": "127.0.0.1","PORT": 3306,"USER": "root","PASSWORD": ""}}__init__ 文件import pymysqlpymysql.install_as_MySQLdb()# 1. 先去 models.py 文件中书写一个类class User(models.Model):# 相当于 id int primary key auto_incrementid = models.AutoField(primary_key=True)# name char(32)name = models.CharField(max_length=32)# password intpassword = models.IntegerField()# 2. 数据库迁移命令1. python manage.py makemigrations 将操作记录记录到小本本上(makemigrations 文件夹)2. python manage.py migrate 将操作真正同步到数据库中# 只要你修改了 models.py 中和数据库有关的代码,你就必须重新执行上述的两条命令# 如果创建表时,不定义字段主键时,orm 会自动创建一个名为 id 的主键# Create your models here.class User(models.Model):"""CharField 必须要有 max_length 参数,不指定会报错verbase_name 该参数是所有字段都有的,就是用来对字段的解释"""# 相当于 id int primary key auto_incrementid = models.AutoField(primary_key=True, verbose_name="主键")# name char(32)name = models.CharField(max_length=32,verbose_name="用户名")# password intpassword = models.IntegerField(verbose_name="密码")
字段的增删改查
# 字段的增加1. 直接在终端内给出 默认值2. 该字段可以为空,或者直接设置默认值info = models.CharField(verbose_name="个人简介", max_length=32, null=True) # 该字段可以为空hobby = models.CharField(max_length=32, verbase_name="爱好", default="study") # 直接设置默认值# 字段的修改直接修改代码,执行数据库迁移的两条命令即可# 字段的删(不要轻易操作)将对应的字段注释,并执行数据库迁移命令执行完毕之后,数据消失"""在操作 models.py 文件的时候一定要细心千万不要注释一些字段执行迁移命令之前最好先检查一下自己写的代码"""
数据的增删改查
# 查询res= models.User.objects.filter(name=username)user_obj = models.User.objects.all()return render(request, "usrelist.html", locals())"""返回值暂时当作 列表套对象的格式它也支持索引取值 切片操作 但是不支持负数索引它也不推荐索引的方式取值user_obj = models.User.objects.filter(name=username).first()"""filter 可以携带多个参数,参数与参数之间默认是 and 关系,可以把 filter 当作 where# 增加res = models.User.objects.create(name=username, password=password)# 返回值是当前被创建的对象本身# 第二种user_obj = models.User(name=username, password=password)user_obj.save() # 保存数据
数据的查、改、删
# 先将数据库中的数据全部展示到前端,然后给每一个数据两个按钮,一个编辑一个删除# 编辑功能# 点击编辑按钮朝后端发送编辑数据的请求"""如何告诉后端用户想要编辑哪条数据将编辑按钮所在的那一行数据的主键值告诉后端/url/?user_id={{ user_obj.id }}"""# 后端查询出用户想要编辑的数据并展示def useredit(request):edit_id = request.GET.get("id")user_obj = models.User.objects.filter(id = edit_id).first()if request.method == "POST":name = request.POST.get("username")password = request.POST.get("password")# 编辑数据# 方法一# 批量操作,只更新修改的数据,效率较高# models.User.objects.filter(id=edit_id).update(name=name, password=password)# 方法二,效率较低,将数据全部更新一遍,无论该字段是否被修改user_obj.name = nameuser_obj.password = passworduser_obj.save()# 跳转页面return redirect("/userlist/")return render(request, "useredit.html", locals())# 删除功能跟编辑功能类似def userdelete(request):delete_id = request.GET.get("id")# 删除数据models.User.objects.filter(id=delete_id).delete()return redirect("/userlist/")"""真正的删除功能应该要二次确认,我们这里先不做删除数据内部其实并不是真正的删除,我们会根据添加一个标识字段来表示当前数据是否被删除,如果数据被删除仅仅只是将字段修改一个状态"""name passwordis_deleteaoteman 123 0alterman123 1
代码
urls.py
from django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [url(r'^admin/', admin.site.urls),url(r'^login/', views.login),url(r"^regin/", views.regin),url(r"^userlist/", views.userlist),url(r"^useredit/", views.useredit),url(r"^userdelete/", views.userdelete),]
views.py
from django.shortcuts import render, HttpResponse, redirectfrom django.http import JsonResponsefrom app01 import models# Create your views here.def login(request):if request.method == "POST":username = request.POST.get("username")message = models.User.objects.filter(name=username).first()if message is None:return HttpResponse("该用户不存在")password = request.POST.get("password")user_password = message.posswordif int(password) == user_password:user_obj = models.User.objects.all()return redirect('/userlist/', locals())![请添加图片描述](https://img-/256727490a004e24b28b5164e8714282.gif)else:return HttpResponse("密码错误")return render(request, "login.html")def regin(request):# 用户注册if request.method == "POST":username = request.POST.get("username")password = request.POST.get("password")hobby = request.POST.get("hobby")# 增添到数据库中models.User.objects.create(name=username, possword = password, hobby=hobby)user_message = models.User.objects.all()return redirect("/login/")return render(request, "register.html")def userlist(request):user_obj = models.User.objects.all()return render(request, "usrelist.html", locals())def useredit(request):id = request.GET.get("id")user_obj = models.User.objects.filter(id = id).first()if request.method == "POST":username = request.POST.get("username")password = request.POST.get("password")models.User.objects.filter(id=id).update(name=username, possword=int(password))user_obj = models.User.objects.all()return render(request, "usrelist.html", locals())return render(request, "useredit.html", locals())def userdelete(request):id = request.GET.get('id')models.User.objects.filter(id=id).delete() # 实际上删除数据还需要二次确认return redirect("/userlist/")
register.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title>{% load static %}<script src="{% static "others/JQuery3.6.0.js" %}"></script><link rel="stylesheet" href="{% static 'others/bootstrap-3.4.1-dist/css/bootstrap.min.css' %}"><script src="{% static 'others/bootstrap-3.4.1-dist/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><p><input type="checkbox" name="hobby" value="111">111<input type="checkbox" name="hobby" value="222">222<input type="checkbox" name="hobby" value="333">333</p><input type="submit" class="btn-warning btn-block"></form></div></div></div></body></html>
login.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title>{% load static %}<script src="{% static 'others/JQuery3.6.0.js' %}"></script><link rel="stylesheet" href="{% static 'others/bootstrap-3.4.1-dist/css/bootstrap.min.css' %}"><script src="{% static 'others/bootstrap-3.4.1-dist/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><p><input type="checkbox" name="hobby" value="111">111<input type="checkbox" name="hobby" value="222">222<input type="checkbox" name="hobby" value="333">333</p><input type="submit" class="btn-success btn-block"></form></div></div></div></body></html>
userlist.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title>{% load static %}<script src="{% static "others/JQuery3.6.0.js" %}"></script><link rel = "stylesheet" href = "{% static 'others/bootstrap-3.4.1-dist/css/bootstrap.min.css' %}" ><script src = "{% static 'others/bootstrap-3.4.1-dist/js/bootstrap.min.js' %}" ></script></head><body><div class="container"><h1 class="text-center">数据展示</h1><div class="row"><div class="col-md-8 col-md-offset-2"><table class="table table-bordered table-striped table-hover"><tr><th>用户名</th><th>密码</th><th>介绍</th><th>爱好</th><th>操作</th></tr>{% for foo in user_obj %}<tr><td>{{ foo.name }}</td><td>{{ foo.possword }}</td><td>{{ foo.info }}</td><td>{{ foo.hobby }}</td><td><a href="/useredit/?id={{ foo.id }}" class="btn btn-primary btn-xs">编辑</a><a href="/userdelete/?id={{ foo.id }}" class="btn btn-danger btn-xs">删除</a></td></tr>{% endfor %}</table></div></div></div></body></html>
useredit.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title>{% load static %}<script src="{% static "others/JQuery3.6.0.js" %}"></script><link rel = "stylesheet" href = "{% static 'others/bootstrap-3.4.1-dist/css/bootstrap.min.css' %}"><script src = "{% static 'others/bootstrap-3.4.1-dist/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={{user_obj.name }}></p><p>password: <input type="text" name="password" class="form-control" value={{user_obj.password }}></p><input type="submit" class="btn-warning btn-block"></form></div></div></div></body></html>
运行演示
如果觉得《DJango 学习(6)—— Django 数据库连接以及简单的前后端数据交互》对你有帮助,请点赞、收藏,并留下你的观点哦!