计算机基础知识50

数据的增删改查(insert update delete select)

用户列表的展示:

把数据表中得用户数据都给查询出来展示在页面上

  1. 查询
python 复制代码
from app01 import models
models.UserInfo.objects.all() # 查询所有的字段信息和数据
res=models.UserInfo.objects.first() # 查询一条,而且是第一条,queryset对象,列表套对象的形式
if res:
    res[0]
try:
    res[0]
# 它是支持索引取值的,如果是第一条就直接first()
select * from userinfo where username ='' and password = '';
res=models.UserInfo.objects.filter(username='', password='').first()  # and
res=models.UserInfo.objects.filter(username='').filter(password='').filter().first() # and
"""链式表达式的思想,jQuery中也有这样的写法"""
models.UserInfo.objects.all()[0]
models.UserInfo.objects.all()[0:2] # 支持切片
  1. 增加
python 复制代码
models.UserInfo.objects.create(username='', password='')
res=models.UserInfo(username='', password='')
res.save() # 真正的操作数据库

3、修改数据的逻辑分析

1. 先确定修改哪条记录------>怎么样确定修改哪条记录?

2. 通过什么字段可以确定唯一一条记录? 主键id,要携带主键id到后端.

3. 在后端接收主键id值,然后根据这个id值再去表中查询数据,查询一条

4. 然后把查询的数据在渲染到页面中,然后在修改

python 复制代码
models.UserInfo.objects.filter(pk=1).update(username='', password='')
res=models.UserInfo.objects.first()
res.username='';
res.password=''
res.save()    # 真正的操作数据库

4、删除功能的分析

1. 给删除按钮加一个链接,携带当前记录的id值

2. 后端要接收这个主键id值

3. 后端直接执行删除操作

python 复制代码
models.UserInfo.objects.filter(pk=1).delete()
res.delete()

数据的增删改查汇总

"views.py"

python 复制代码
from django.shortcuts import render,HttpResponse,reverse,redirect

# Create your views here.

def home(request):
    print('request')
    return HttpResponse('/home/')

from app01 import models

def login(request):
    print(request.method,type(request.method))
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        print(request.POST.getList('hobby'))
        res = models.UserInfo.objects.filter(username='123',password='123').all()
        print(res)
        res.username=''
        res.password=''
        if username == 'kevin' and password == '123':
            print('登录成功')
            models.UserInfo.objects.create(username='kevin',password='123')
            return redirect('/index/')
        else:
            return HttpResponse("用户名或密码错误")

    print(request.GET)
    print(request.GET.get('a'))
    print(request.GET.get('b'))
    print(request.GET.get('c'))
    print(request.GET.get('c'))
    print(request.GET.getlist('c'))
    return render(request,'login.html')

def userlist(request):
    user_list=models.UserInfo.objects.all()#查询所有信息
    """这里不之处负数切片"""
    # user_list=models.UserInfo.objects.all()[0:2] # 查询所有的数据
    '''支持for循环'''
    # for i in user_list:
    #     print(i.gender)
    ## queryset对象就是一个列表套对象的形式
    # <QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
    # print(user_list[0])
    print(user_list[0].username)
    return  render(request,'userlist.html',locals())

def edit(request):
    edit_id = request.GET.get('id')
    edit_ibj = models.UserInfo.objects.filter(id=edit_id).first()
    if request.method == 'POST':
        hidden_id = request.POST.get('hidden_id')
        username = request.POST.get('username')
        password = request.POST.get('password')
        gender = request.POST.get('gender')
        # 修改
        affect_rows = models.UserInfo.objects.filter(pk=hidden_id).update(username=username,password=password,gender=gender)
        return redirect('/userlist/')
    return render(request,'edit.html',locals())

def delete(request):
    delete_id = request('/userlist/')
    return redirect('/userlist/')

def add(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        gender = request.POST.get('gender')
        user_obj = models.UserInfo(username=username,password=password,gender=gender)
        user_obj.save()
        return redirect('/userlist/')
    return render(request,'add.html')

def ab_render(request):
    user_dict1 = {'username':'kevin','password':123}
    user_dict1 = {'a':1}
    print(locals())
    return render(request,'')

"urls.py"

python 复制代码
from django.contrib import admin
from django.urls import path
from app01 import views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', views.login),
    path('home/', views.home),
    path('userlist/', views.userlist),
    path('edit/', views.edit),
    path('delete/', views.delete),
    path('add/', views.add),
    path('ab_render/', views.ab_render),

]

"models.py"

python 复制代码
from django.db import models

# Create your models here.

class UserInfo(models.Model):
    username = models.CharField(max_length=32,verbose_name='用户名')
    password = models.CharField(max_length=64,verbose_name='密码')
    gender = models.CharField(max_length=32)

def __str__(self):
    return self.username

"init.py"

python 复制代码
import pymysql
pymysql.install_as_MySQLdb()

前端:"ab_render.html"

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

{{ user_dict.username }}
{{ user_dict.password }}
{{ user_dict1 }}
{{ user_dict1.a }}
</body>
</html>

"add.html"

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <link rel="stylesheet" href="bootstrap-3.4.1-dist/css/bootstrap.min.css">
    <script src="bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <h1 class="text-center">添加页面</h1>
        <form action="" method="post">
            <div class="form-group">
                用户名:<input type="text" class="form-control" name="username">
            </div>
            <div class="form-group">
                密码:<input type="password" class="form-control" name="password">
            </div>
            <div class="form-group">
                性别:<input type="text" class="form-control" name="gender">
            </div>
        </form>
    </div>
</div>
</body>
</html>

"edit.html"

python 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <h1 class="text-center">修改页面</h1>
        <form action="" method="post">
            <input type="hidden" value="{{ edit_obj.pk }}" name="hidden_id">
            <div class="form-group">
                用户名: <input type="text" class="form-control" name="username" value="{{ edit_obj.username }}">
            </div>
            <div class="form-group">
                密码: <input type="password" class="form-control" name="password" value="{{ edit_obj.password }}">
            </div>
            <div class="form-group">
                性别: <input type="text" class="form-control" name="gender" value="{{ edit_obj.gender }}">
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-info btn-block" value="提交">
            </div>
        </form>
    </div>
</div>
</body>
</html>

"index.html"

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <link rel="stylesheet" href="bootstrap-3.4.1-dist/css/bootstrap.min.css">
    <style>
        h1{
            color: hotpink;
        }
    </style>
</head>
<body>
<h1>第一个模板文件</h1>
</body>
</html>

"login.html"

python 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <link rel="stylesheet" href="bootstrap-3.4.1-dist/css/bootstrap.min.css">
    <script src="bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <h1 class="text-center">登录页面</h1>
        <form action="" method="post">
            <div class="form-group">
                用户名:<input type="text" class="form-control " name="username">
            </div>
            <div class="form-group">
                密码:<input type="password" class="form-control " name="password">
            </div>
            <div class="form-group">
                <input type="checkbox" name="hobby" value="a">
                <input type="checkbox" name="hobby" value="b">
                <input type="checkbox" name="hobby" value="c">
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-success btn-block" value="登录">
            </div>
        </form>
    </div>
</div>
</body>
</html>

"userlist.html"

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <h1 class="text-center">用户列表</h1>
        <a href="/add/" class="btn btn-success">添加用户</a>
        <table class="table table-striped table-hover table-bordered">
            <thead>
            <tr>
                <th>ID</th>
                <th>username</th>
                <th>password</th>
                <th>gender</th>
                <th>action</th>
            </tr>
            </thead>
            <tbody>
            {% for user in user_list %}
                <tr>
                    <td>{{ user.id }}</td>
                    <td>{{ user.username }}</td>
                    <td>{{ user.password }}</td>
                    <td>{{ user.gender }}</td>
                    <td>
                        <a href="/edit/?id={{ user.id }}" class="btn btn-success">修改</a>&nbsp;&nbsp;&nbsp;
                        <a href="/del/?id={{ user.pk }}" class="btn btn-danger">删除</a>
                    </td>
                </tr>
            {% endfor %}


            </tbody>
        </table>
    </div>
</div>
</body>
</html>

如何创建表关系(一对一 一对多 多对多)

换位思考法判断表关系

图书表和出版社表 >>> 一对多 >>> 图书表是多,出版社是一 >>> 建在多的一方

图书表和作者表 >>> 多对多 >>> 需要第三张表

作者表和作者详情表 >>> 一对一 >>> 外键字段一般建在查询频率较高的

在Django中如何创建表关系

"""回头复习表关系"""

python 复制代码
class Book(models.Model):
    title = models.CharField(max_length=64)
    """
    max_digits=None,:总位数
    decimal_places=None:小数位数
    """
    # price decimal(8,2)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    # publish_id = models.ForeignKey(to='Publish', to_field='id')
    """对于外键字段关系,会自动帮我们拼接_id"""
    publish = models.ForeignKey(to='Publish')
    """authors它是一个虚拟字段,它不会实际在表中创建出来这个字段,这一句可以自动帮助我们创建出来第三张表"""
    authors = models.ManyToManyField(to='Author')

"""出版社表"""

python 复制代码
class Publish(models.Model):
    name = models.CharField(max_length=64)
    addr = models.CharField(max_length=64)

"""作者表"""

python 复制代码
class Author(models.Model):
    name = models.CharField(max_length=64)
    author_detail = models.OneToOneField(to='AuthorDetail')

"""作者详情表"""

python 复制代码
class AuthorDetail(models.Model):
    phone = models.CharField(max_length=64)
    email = models.CharField(max_length=64)

Django的请求生命周期流程图

"""它可以帮助你们熟练django的一个完整执行流程"""

今日思维导图:

相关推荐
Open-AI几秒前
Python如何判断一个数是几位数
python
桀桀桀桀桀桀2 分钟前
数据库中的用户管理和权限管理
数据库·mysql
极客代码4 分钟前
【Python TensorFlow】入门到精通
开发语言·人工智能·python·深度学习·tensorflow
义小深6 分钟前
TensorFlow|咖啡豆识别
人工智能·python·tensorflow
疯一样的码农10 分钟前
Python 正则表达式(RegEx)
开发语言·python·正则表达式
superman超哥1 小时前
04 深入 Oracle 并发世界:MVCC、锁、闩锁、事务隔离与并发性能优化的探索
数据库·oracle·性能优化·dba
用户8007165452001 小时前
HTAP数据库国产化改造技术可行性方案分析
数据库
进击的六角龙1 小时前
Python中处理Excel的基本概念(如工作簿、工作表等)
开发语言·python·excel
一只爱好编程的程序猿2 小时前
Java后台生成指定路径下创建指定名称的文件
java·python·数据下载
Aniay_ivy2 小时前
深入探索 Java 8 Stream 流:高效操作与应用场景
java·开发语言·python