Django 之多对多关系
生活随笔
收集整理的這篇文章主要介紹了
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_nameedit_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.nameif 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>?
轉載于:https://www.cnblogs.com/wjs521/p/9804581.html
總結
以上是生活随笔為你收集整理的Django 之多对多关系的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: YARN学习笔记
- 下一篇: Go之十大经典排序算法