当前位置:网站首页>第七单元 ORM表关系及操作
第七单元 ORM表关系及操作
2022-08-02 14:01:00 【czy1206527605】
一.多对一关系
类似于一个公司有多个员工,多个员工隶属于一个公司。
可以用foreign key来指定多对一的关系
class Department(models.Model): # 主表
dep_name = models.CharField(max_length=20,verbose_name='部门名称')
desc = models.CharField(max_length=20,verbose_name='部门描述')
class Meta: # 从表
verbose_name = "部门表"
verbose_name_plural = verbose_name
db_table = 'department'
def __str__(self):
return self.dep_name
class Employee(models.Model):
emp_name = models.CharField(max_length=20,verbose_name='姓名')
job = models.CharField(max_length=20,verbose_name='职位')
salary = models.IntegerField(verbose_name='工资')
dapartment = models.ForeignKey(to=Department, on_delete=models.CASCADE, verbose_name='部门')
class Meta:
verbose_name = "员工表"
verbose_name_plural = verbose_name
db_table = 'employee'
def __str__(self):
return self.emp_name
1.级联操作:主表数据删除,从表怎么办
黑板老大 小弟
挂了 殉情 CASCADE
挂了 抢救过来,不让挂 PROTECT
挂了 不要老大了,自己过自己的 SET_NULL
挂了 再找一个新的老大 SET_DEFAULT
2.多对一的增删改操作
增
class DepartmentView(View):
def get(self,request):
department = Department.objects.all()
return render(request,'department.html',{'department':department})
<以下代码为增加操作,上面的代码为方便写路由>
def post(self,request):
emp_name = request.POST.get('emp_name')
job = request.POST.get('job')
salary = request.POST.get('salary')
dapartment = request.POST.get('dapartment')
try:
Employee.objects.create(
emp_name=emp_name,
job=job,
salary=salary,
dapartment_id=dapartment)
except Exception as e:
print(e)
return HttpResponse("添加失败")
return redirect('/dep/')
url路由
path('dep/',views.DepartmentView.as_view()),
删
class DelEmployeeView(View):
def get(self,request,id):
employee_data = Employee.objects.get(id=id)
dep_id = employee_data.dapartment_id
employee_data.delete()
return redirect(f'/emp/{dep_id}')
url路由
path('delemp/<int:id>/',views.DelEmployeeView.as_view()),
改
class UpdateEmployeeView(View):
def get(self,request,id):
try:
employee_data = Employee.objects.get(id=id)
except Exception as e:
print(e)
return HttpResponse("页面不存在")
return render(request,'index.html',{'employee':employee_data})
def post(self,request,id):
emp_name = request.POST.get('emp_name')
job = request.POST.get('job')
salary = request.POST.get('salary')
dapartment = request.POST.get('dapartment')
try:
Employee.objects.filter(id=id).update(
emp_name = emp_name,
job = job,
salary = salary,
dapartment_id = dapartment
)
except Exception as e:
print(e)
return HttpResponse('修改数据失败')
return redirect('/dep/')
url路由
path('updateemp/<int:id>/',views.UpdateEmployeeView.as_view())
点击主表某字段以获取从表对应信息
class EmployeeView(View):
def get(self,request,id):
employee = Employee.objects.filter(dapartment_id=id)
return render(request,'employee.html',{'employee':employee})
url路由
path('emp/<int:id>/',views.EmployeeView.as_view()),
二.一对一关系
类似于一个人只能有一个对象,一个人不能有多个对象
使用OneToOneField用来定义一对一关系
一对一的查询
主表查子表将子表名小写
子表查主表直接用连接的字段来查即可
三.多对多关系
类似于一个音乐家隶属于多个乐队,而一个乐队有多个音乐家。
使用ManyToManyField字段定义
数据的添加
模型类.objects.create(需要添加的字段=‘’)
乐队 = 表名.objects.create(表名小写_name=“Jack”)
数据的删除
乐队.表名.remove(音乐家)
数据的查询
主表查子表
主表.band_set.all()
子表查主表
子表.主表字段.all()
四.单表搜索功能
model视图代码
class Staff(models.Model):
name = models.CharField(max_length=20,verbose_name='姓名')
job = models.CharField(max_length=20,verbose_name='职位')
salary = models.IntegerField(verbose_name='工资')
department = models.CharField(max_length=20,verbose_name='部门')
templates视图代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>主页</h3>
<table border="1px" cellspacing="0">
<tr>
<th>编号</th>
<th>姓名</th>
<th>职位</th>
<th>工资</th>
<th>部门</th>
<th>操作一</th>
</tr>
{% for staffs in staff %}
<tr>
<td>{
{ staffs.id }}</td>
<td>{
{ staffs.name }}</td>
<td>{
{ staffs.job }}</td>
<td>{
{ staffs.salary }}</td>
<td>{
{ staffs.department }}</td>
<td><a href="/del/{
{ staffs.id }}/">删除</a> </td>
</tr>
{% endfor %}
</table>
<h4>搜索内容板块</h4>
<form method="get" action="/search/">
姓名:<input type="text" name="name">
<input type="submit" value="搜索">
</form>
</body>
</html>
路由代码
path('search/',views.SearchStaffView.as_view())
view视图代码
class SearchStaffView(View):
def get(self,request):
name = request.GET.get('name')
try:
staff_data = Staff.objects.get(name__contains=name)
except Exception as e:
print(e)
return HttpResponse("搜索数据不存在")
return HttpResponse(f"搜索到的数据为:{staff_data.name},{staff_data.job},{staff_data.salary},{staff_data.department}")
边栏推荐
猜你喜欢
Some impressions of the 519 plummet 2021-05-21
如何解决mysql服务无法启动1069
deal!It's July 30th!
Interview | with questions to learn, Apache DolphinScheduler Wang Fuzheng
binary search && tree
关于市场后市的发展预测? 2021-05-23
Mysql's case the when you how to use
IDEA打包jar包
【Tensorflow】AttributeError: ‘_TfDeviceCaptureOp‘ object has no attribute ‘_set_device_from_string‘
专访|带着问题去学习,Apache DolphinScheduler 王福政
随机推荐
drf视图组件
idea社区版下载安装教程_安装天然气管道的流程
The most complete ever!A collection of 47 common terms of "digital transformation", read it in seconds~
网络安全第二次作业
【ONE·Data || Getting Started with Sorting】
【Tensorflow】AttributeError: '_TfDeviceCaptureOp' object has no attribute '_set_device_from_string'
deal!It's July 30th!
Detailed explanation of ORACLE expdp/impdp
专访|带着问题去学习,Apache DolphinScheduler 王福政
GTK:Gdk-CRITICAL **: IA__gdk_draw_pixbuf: assertion ‘GDK_IS_DRAWABLE (drawable)’ failed
Object detection scene SSD-Mobilenetv1-FPN
第二讲 软件生命周期
Tornado框架路由系统介绍及(IOloop.current().start())启动源码分析
Image retrieval method based on deep learning!
ORACLE expdp/impdp详解
栈 && 队列
redis分布式锁和看门狗的实现
rhce第三天作业
WiFi Association&Omnipeek抓包分析
How to solve 1045 cannot log in to mysql server