Django 之多对多关系
1. 多对多关系
作者 <--> 书籍
1. 表结构设计
1. SQL版
-- 创建作者表
create table author(
id int primary key auto_increment,
name varchar(32) not null
);
-- 创建作者和书的关系表
create table author2book(
id int primary key auto_increment,
author_id int not null,
book_id int not null,
constraint fk_author foreign key (author_id) references author(id) on delete cascade on update cascade,
constraint fk_book foreign key (book_id) references book(id) on delete cascade on update cascade
);
2. ORM版
1. 第一版:
自己创建第三张表
2. 第二版
让ORM帮我们创建第三张表
models.ManyToManyField()
3. 第三版
待补充...(ORM进阶操作的时候)
2. 作者的增删改查
1. 查询
# 展示作者
def author_list(request):
# 1. 去数据库查询到所有的作者
author_data = Author.objects.all()
for author in author_data:
print(author)
# 取到每个作者出版的书籍
# print(author.books) # 是一个ORM提供的桥梁(工具),帮我找对应关系
print(author.books.all())
# 2. 在页面上展示出来
return render(request, 'author_list.html', {'author_list': author_data})
author_obj.books --> 得到的只是一个关联关系,并不能拿到数据
author_obj.books.all() --> 得到和我这个作者关联的所有书籍对象列表
2. 添加
1. add()
# 添加作者
def add_author(request):
if request.method == 'POST':
# 1. 取到用户填写的信息
new_author_name = request.POST.get('author_name')
# book_ids = request.POST.get('books') # -->这个只能取到一个值
book_ids = request.POST.getlist('books')
# print(new_author_name)
# print(book_ids)
print(request.POST.getlist('hobby'))
print('-' * 120)
# 2. 添加到数据库
# 2.1 创建新的作者
author_obj = Author.objects.create(name=new_author_name)
# 2.2 创建新作者和书的对应关系
author_obj.books.add(*book_ids) # 参数是一个一个单独的书籍id值
# author_obj.books.set(book_ids) # 参数是书籍id值的列表
# 3. 跳转到作者列表页面
return redirect('/author_list/')
# 1. 返回一个页面给用户,让用户填写作者信息
# 2. 获取所有的书籍信息
book_data = Book.objects.all()
return render(request, 'add_author.html', {'book_list': book_data})
3. 删除
# 删除作者
def delete_author(request):
# 1. 取到要删除的作者的id值
delete_author_id = request.GET.get('kangchen')
age = request.GET.get('age')
print(delete_author_id)
print(age)
# 2. 同过id找到数据,并删除
Author.objects.filter(id=delete_author_id).delete()
# 3. 让用户再访问作者列表页面
return redirect('/author_list/')
4. 编辑
# 编辑作者
def edit_author(request):
# 1. 取到要编辑的作者的id值
edit_author_id = request.GET.get('id')
# 2. 找到要编辑的作者对象
edit_author_obj = Author.objects.get(id=edit_author_id) if request.method == 'POST':
# 3. 拿到编辑之后的数据
new_author_name = request.POST.get('author_name')
new_book_ids = request.POST.getlist('book_ids')
# 4. 去数据库修改
# 4.1 修改作者表
edit_author_obj.name = new_author_name
edit_author_obj.save()
# 4.2 修改作者和书的关系表
edit_author_obj.books.set(new_book_ids)
# 5. 跳转到作者列表页面
return redirect('/author_list/') # 2.2 找到所有的书籍对象
book_data = Book.objects.all()
# 3. 返回一个页面
return render(request, 'edit_author.html', {'author': edit_author_obj, 'book_list': book_data})
1. 模板语言中
{% if book in author.books.all %}
2. ORM编辑多对多
1. 不能直接操作第三张关系表
2. 借助ORM给提供的方法
- all()
- add(id1,id2)
- set([id1, id2])
- clear()
3. Django模板语言
1. for循环
1. forloop.last
{% if forloop.last %}
...
2. empty
{% for i in x %}
...
{% empty %}
...
{% endfor %}
4. 上传文件
form表单上传文件
views.py中
# 上传文件
def upload(request):
if request.method == 'POST':
# 1. 取到用户发送的数据
print(request.POST)
print(request.FILES)
file_obj = request.FILES.get('file_name')
print(file_obj.name)
# 判断当前是否存在
file_name = file_obj.name
if os.path.exists(os.path.join(settings.BASE_DIR, file_name)):
# 如果存在同名的文件
name, suffix = file_name.split('.')
name += '2'
file_name = name + '.' + suffix
# 从上传文件对象里 一点一点读取数据,写到本地
with open(file_name, 'wb') as f:
# 从上传文件对象里 一点一点读取数据
for chunk in file_obj.chunks():
f.write(chunk)
# 1. 第一次GET请求来,应该给用户返回一个页面,让用户选择文件
return render(request, 'upload.html')
html文件中
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>上传文件示例</title>
</head>
<body> <h1>上传文件</h1>
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="test">
<input type="file" name="file_name">
<input type="submit">
</form> </body>
</html>
Django 之多对多关系的更多相关文章
- Django中多对多关系的orm表设计
作者的管理 1.设计表结构 出版社 书籍 作者 一个出版社出版多个书籍 1对多 书籍和作者的关系:一个作者写多本书,一本书可以是多个作者写.多对多 1)创建一张表,表中多对多的数据关系.使用 多对多 ...
- Linux下开发python django程序(django数据库多对多关系)
1.多对多关系数据访问 models.py设置 from django.db import models # Create your models here. sex_choices=( ('f',' ...
- django 的多对多关系
django里自带的多对多表创建 其实就是两个多对一关系各自关联,在第三张表上 多对多的增加 add()可以传数值 例如 add(1)或数组 add(*[2,3]) 多对多反向操作 自己创建第三张表, ...
- django ORM模型表的一对多、多对多关系、万能双下划线查询
一.外键使用 在 MySQL 中,如果使用InnoDB引擎,则支持外键约束.(另一种常用的MyIsam引擎不支持外键) 定义外键的语法为fieldname=models.ForeignKey(to_c ...
- 15)django-ORM(多对多关系)
django ORM多对多关系使用 一:多对多关系创建 多对多关系创建:分为两种情况,手动创建和django自动创建 1)手动创建:自定义关系表 通过自定义表,通过models.ForeignKey创 ...
- django笔记-模型数据模板呈现过程记录(多对多关系)
首先,推荐一个网址:http://www.tuicool.com/articles/BfqYz2F,因为这里的比我的要有条理,更有利于各位的理解. 以下仅为为个人一次不完整的笔记: 环境:ubuntu ...
- Django 一对多,多对多关系解析
[转]Django 一对多,多对多关系解析 Django 的 ORM 有多种关系:一对一,多对一,多对多. 各自定义的方式为 : 一对一: OneToOneField ...
- django -- 多对多关系的实现
在django中表和表之间的多对多关系有两种实现方案: 方案一:直接使用django自动实现的多对多关系. 方案二:自己写连接表.然而告诉django在实现多对多关系时要使用的连接表. 一.方案一: ...
- django前端渲染多对多关系(比如一本书的作者有哪些)
自己遇到的问题是,前端渲染不出多对多关系,咨询Yuan后解决,特此记录. urls.py from django.conf.urls import url from book import views ...
随机推荐
- java json字符串与对象转换
下载引入包gson-2.0.jar 1.字符转数据 final Map map = new HashMap();map.put("contents", "[{\&q ...
- ASP.NET Core MVC 概述
https://docs.microsoft.com/zh-cn/aspnet/core/mvc/overview?view=aspnetcore-2.2 ASP.NET Core MVC 概述 20 ...
- SqlDataSource.FilterExpression Property
SqlDataSource.FilterExpression Property 定义 命名空间: System.Web.UI.WebControls Assembly: System.Web.dll ...
- 选择、操作web元素-3
11月5日 Selenium 作业 3 登录 51job , http://www.51job.com 输入搜索关键词 "python", 地区选择 "杭州"( ...
- JAVA版开源微信管家—JeeWx捷微3.1小程序版本发布,支持微信公众号,微信企业号,支付窗
支持小程序,JeeWx捷微3.1小程序版本发布^_^ JeeWx捷微V3.1--多触点小程序版本管理平台(支持微信公众号,微信企业号,支付窗) JeeWx捷微V3.1.0版本紧跟微信小程序更新,在原有 ...
- 自动配置IE代理脚本
http://www.cnblogs.com/ttyp/archive/2005/11/18/279124.html
- keal
I remember the wonderful moment you appeared before me, like a fleeting vision, like a genius of pur ...
- LG Optimus L90 [D415] T-Mobile 刷机
1 先使用[ROOT大师]ROOT手机. 2 执行以下ADB命令. adb shell su //备份 dd /by-name/laf of=/sdcard/laf.img. //清除 dd /by- ...
- git-04 同意分支合并
https://blog.csdn.net/boysky0015/article/details/78185879/
- Hibernate 再接触 多对一与一对多
多对一单向关联 数据库设计: 错误做法:在多方加外键 在多这一方加外键 第一种 annotation Group.java package com.bjsxt.hibernate; import ja ...