python对数据库进行增删改查操作

第六单元

案例数据进行增删改查

在settings里配置项目
安装数据库
编写两个模型类

from django.db import models
# Create your models here.
# models.Model 继承
class Department(models.Model):
#
    dep_name = models.CharField(max_length=10,verbose_name="部门名称")
    desc = models.CharField(max_length=10,verbose_name="部门描述")
    class Meta:
        verbose_name = '部门表'
        verbose_name_plural =verbose_name
        db_table = 'depart6'
    def __str__(self):
        return self.dep_name

class Employee(models.Model):
    emp_name = models.CharField(max_length=10,verbose_name="姓名")
    job = models.CharField(max_length=10,verbose_name="职业")
    salary = models.IntegerField(verbose_name="工资")
    # 级联操作
    department =models.ForeignKey(to = Department,on_delete=models.CASCADE,verbose_name="部门") #外键
    class Meta:
        verbose_name = '员工表'
        # 复数形式
        verbose_name_plural =verbose_name
        db_table = 'depar6'
    def __str__(self):
        return self.emp_name
# 文件迁移,执行迁移文件
# python manage.py makemigrations
# python manage.py migrate
# pythom manage.py createsuperuser

将主表内容展示出来

1、定义主表视图

# 导入部门模型类,和视图
from django.shortcuts import render
from myapp.models import Department
from django.views import View

class zhu(View):
    def get(self,request):
        date = Department.objects.all()
        return render(request,'zhu.html',{'datas':date})

2、子路由路由

from myapp import views
from django.urls import path
urlpatterns = [
    path('zhu/',views.zhu.as_view()),

]

3、定义页面进行数据渲染

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <table border="1px" width="500px">
        <tr>
            <td>编号td>
            <td>名称td>
            <td>名称td>
        tr>
        {% for data in datas %}
        <tr>
            <td>{{ data.id }}td>
            <td>
                {{ data.dep_name }}
            td>
            <td>{{ data.desc }}td>
        tr>
        {% endfor %}

    table>
body>
html>

点击部门会跳转到对应的员工信息表

1、定义员工视图

class yuan(View):
	# 这里的id就是html页面传入路由的id
    def get(self,request,id):
        # 过滤出部门id和传入的id相同的数据
        data = Employee.objects.filter(department_id = id).order_by('salary')
        return render(request,'yuan.html',{'datas':data})

2、路由

from myapp import views
from django.urls import path

urlpatterns = [
	#动态路由根据部门的id查询对应的员工
    path('yuan//',views.yuan.as_view()),

]

3、点击进行跳转

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <table border="1px" width="500px">
        <tr>
            <td>编号td>
            <td>名称td>
            <td>名称td>
        tr>
        {% for data in datas %}
        <tr>
            <td>{{ data.id }}td>
            <td>
            {# 点击部门名,会由href跳转到对应的路由上,并传递过去id   以post方法进行传递#}
                <a href="/yuan/{{ data.id }}/" methods="post">
                {{ data.dep_name }}
                 a>
            td>
            <td>{{ data.desc }}td>
        tr>
        {% endfor %}

    table>
body>
html>

4、员工的页面

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <table border="1px" width="500px">
        <tr>
            <td>编号td>
            <td>姓名td>
            <td>职业td>
            <td>工资td>
            <td>部门td>
        tr>
        {% for data in datas %}
        <tr>
            <td>{{ data.id }}td>
            <td>{{ data.emp_name }}td>
            <td>{{ data.job }}td>
            <td>{{ data.salary }}td>
            <td>{{ data.department }}td>

        tr>
        {% endfor %}
    table>

body>
html>

增加数据

1、定义添加视图

class add(View):
    def post(self,request):
        # 获取添加的数据
        name = request.POST.get('emp_name')
        job = request.POST.get('job')
        salary = request.POST.get('salary')
        department = request.POST.get('department')
        try:
            Employee.objects.create(
                emp_name = name,
                job = job,
                salary = salary,
                department_id = department  #外键使用的id
            )
        except Exception as e:
            print(e)
            return HttpResponse("添加失败")
        return redirect('/zhu/')

2、在员工表下进行添加数据

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<form action="/add/" method="post">
    名字:<input type="text" name="emp_name"><br>
    职业<input type="text" name="job"><br>
    工资<input type="text" name="salary"><br>
    部门<input type="text" name="department"><br>
    <input type="submit" value="添加">
form>
body>
html>

3、配置路由

from myapp import views
from django.urls import path

urlpatterns = [
    path('add/',views.add.as_view()),
]

删除数据

1、定义视图

class delview(View):
    def get(self,request,id):
        # 第一种方法  用get也可以
        # Employee.objects.filter(id=id).delete()
        # return redirect('/zhu/')

        # 第二种方法
        data = Employee.objects.get(id=id)
        dep_id = data.department_id
        data.delete()
        return redirect(f'/yuan/{dep_id}/')

2、在员工页面添加删除按钮

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <table border="1px" width="500px">
        <tr>
            <td>编号td>
            <td>姓名td>
            <td>职业td>
            <td>工资td>
            <td>部门td>
            <td>操作td>
        tr>
        {% for data in datas %}
        <tr>
            <td>{{ data.id }}td>
            <td>{{ data.emp_name }}td>
            <td>{{ data.job }}td>
            <td>{{ data.salary }}td>
            <td>{{ data.department }}td>
            <td>
                {#   点击a发起get请求  #}
                <a href="/del/{{ data.id }}/">删除a>
            td>
        tr>
        {% endfor %}
    table>
body>
html>

3、配置路由

from myapp import views
from django.urls import path

urlpatterns = [
	# 动态路由
    path('del//',views.delview.as_view()),
]

修改

1、修改视图

class update(View):
# 路由传递过来的id
    def get(self,request,id):
        data = Employee.objects.get(id=id)
        # get获取单个数据
        # 将id相同的数据传递到udp页面
        return render(request,'upd.html',{'datas':data})
    def post(self,request,id):
        # 获取uod里面的数据
        name = request.POST.get('name')
        job = request.POST.get('job')
        salary = request.POST.get('salary')
        department = request.POST.get("department")
        try:
            # 只有filter 有update的功能
            Employee.objects.filter(id=id).update(
                emp_name=name,
                job =job,
                salary =salary,
                department_id =department
            )
        except Exception as e:
            print(e)
            return HttpResponse("修改失败")
        return redirect('/zhu/')

2、路由

from myapp import views
from django.urls import path

urlpatterns = [
	# 动态路由传入id 要修改员工的id
    path('upd//',views.update.as_view()),
]

3、点击修改,跳转到修改页面

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <table border="1px" width="500px">
        <tr>
            <td>编号td>
            <td>姓名td>
            <td>职业td>
            <td>工资td>
            <td>部门td>
            <td>操作td>
        tr>
        {% for data in datas %}
        <tr>
            <td>{{ data.id }}td>
            <td>{{ data.emp_name }}td>
            <td>{{ data.job }}td>
            <td>{{ data.salary }}td>
            <td>{{ data.department }}td>
            <td>
                {#   点击a发起get请求  #}
                <a href="/upd/{{ data.id }}/">修改a>
            td>
        tr>
        {% endfor %}
    table>
body>
html>

4、修改页面

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
{# 不用action默认传递到本视图 #}
    <form method="post">
{# value将数据绑定#}
        名字:<input type="text" value="{{ datas.emp_name }}" name="name"><br>
        工作:<input type="text" value="{{ datas.job }}" name="job"><br>
        工资:<input type="text" value="{{ datas.salary }}" name="salary"><br>
        部门:<input type="text" value="{{ datas.department_id }}" name="department"><br>
        <input type="submit" value="修改">
    form>
body>
html>

查询员工

1、查询视图

class search(View):
    def get(self,request):
        name = request.GET.get('name')
        try:
            data = Employee.objects.get(emp_name__contains=name)
        except Exception as e:
            print(e)
            return HttpResponse("查询失败")
         # 直接返回查询的内容
        return HttpResponse(f'{data.emp_name},{data.job},{data.salary},{data.department}')

2、路由

from myapp import views
from django.urls import path

urlpatterns = [
    path('search/',views.search.as_view())
]

3、查询的页面

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<form action="/search/" method="get">
    名字:<input type="text" name="name">
    <input type="submit" value="搜索">
form>
body>
html>

你可能感兴趣的:(python,数据库,django)