python框架之Django(2)-简单的CRUD
写一个简单的项目小例子来了解Django中的O/RM操作
前戏
创建app
#在Django项目根目录下执行 python3 manage.py startapp [app name]
配置数据库连接信息
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # 连接的数据库类型 'HOST': '127.0.0.1', # 连接数据库的地址 'PORT': 3306, # 端口 'NAME': "testdb", # 数据库名称 'USER': 'root', # 用户 'PASSWORD': 'root' # 密码 } }
让Django用pymysql来代替默认的MySQLdb
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import pymysql pymysql.install_as_MySQLdb()
让项目'知道'APP
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login_app.apps.LoginAppConfig' ]
表关系
代码
创建模型
在app下面的models.py文件中定义类,这些类必须继承models.Model
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from django.db import models 2 3 4 class Press(models.Model): 5 ''' 6 出版社 7 ''' 8 id = models.AutoField(primary_key=True) 9 name = models.CharField(max_length=50, unique=True) 10 11 12 class Book(models.Model): 13 ''' 14 书籍 15 ''' 16 id = models.AutoField(primary_key=True) 17 name = models.CharField(max_length=50, unique=True) 18 press = models.ForeignKey(Press) 19 20 21 class Author(models.Model): 22 ''' 23 作者 24 ''' 25 id = models.AutoField(primary_key=True) 26 name = models.CharField(max_length=50, unique=True) 27 book = models.ManyToManyField(Book)
执行命令
python3 manage.py makemigrations # 对比模型和db的差异,记录下将要发生的变更
python3 manage.py migrate # 将记录的变更在数据库中执行
CRUD操作
-
出版社(一对多)
1 from django.shortcuts import render, HttpResponse, redirect 2 from bookapp import models 3 4 def add(request): 5 ''' 6 添加 7 ''' 8 if request.method == 'POST': 9 name = request.POST.get('name') 10 models.Press.objects.create(name=name).save() 11 return redirect('/list_press/') 12 return render(request, 'press/add.html') 13 14 15 def list(request): 16 ''' 17 列表 18 ''' 19 all_list = models.Press.objects.all() 20 return render(request, 'press/list.html', {'list': all_list}) 21 22 23 def edit(request): 24 ''' 25 编辑 26 ''' 27 if request.method == 'POST': 28 id = request.POST.get('id') 29 name = request.POST.get('name') 30 obj = models.Press.objects.get(id=id) 31 obj.name = name 32 obj.save() 33 return redirect('/list_press/') 34 id = request.GET.get('id') 35 obj = models.Press.objects.get(id=id) 36 return render(request, 'press/edit.html', {'press': obj}) 37 38 39 def delete(request): 40 ''' 41 删除 42 ''' 43 id = request.GET.get('id') 44 models.Press.objects.get(id=id).delete() 45 return redirect('/list_press/')
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>添加出版社</title> 6 </head> 7 <body> 8 <form action="/add_press/" method="post"> 9 <p>名称:<input name="name" type="text"></p> 10 <p><input type="submit" value="提交"></p> 11 </form> 12 </body> 13 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>出版社列表</title> 6 </head> 7 <body> 8 <a href="/add_press/">添加</a> 9 <table border="1" style="border-collapse:collapse;"> 10 <tr> 11 <td>序号</td> 12 <td>名称</td> 13 <td>拥有书籍</td> 14 <td colspan="2">操作</td> 15 </tr> 16 {% for press in list %} 17 <tr> 18 <td>{{ forloop.counter }}</td> 19 <td>{{ press.name }}</td> 20 <td>{% for book in press.book_set.all %} 21 {% if forloop.counter == press.book_set.all.count %} 22 {{ book.name }} 23 {% else %} 24 {{ book.name }}, 25 {% endif %} 26 {% endfor %}</td> 27 <td><a href="/edit_press/?id={{ press.id }}">编辑</a></td> 28 <td><a href="/del_press/?id={{ press.id }}">删除</a></td> 29 </tr> 30 {% endfor %} 31 </table> 32 </body> 33 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>修改出版社</title> 6 </head> 7 <body> 8 <form action="/edit_press/" method="post"> 9 <input type="hidden" name="id" value="{{ press.id }}"> 10 <p>名称:<input name="name" type="text" value="{{ press.name }}"></p> 11 <p><input type="submit" value="提交"></p> 12 </form> 13 </body> 14 </html>
-
书籍(多对一&多对多)
1 from django.shortcuts import render, HttpResponse, redirect 2 from bookapp import models 3 4 5 def add(request): 6 ''' 7 添加 8 ''' 9 if request.method == 'POST': 10 press_id = request.POST.get('press_id') 11 name = request.POST.get('name') 12 models.Book.objects.create(name=name, press_id=press_id).save() 13 return redirect('/list_book/') 14 press_list = models.Press.objects.all() 15 return render(request, 'book/add.html', {'press_list': press_list}) 16 17 18 def list(request): 19 ''' 20 列表 21 ''' 22 all_list = models.Book.objects.all() 23 return render(request, 'book/list.html', {'list': all_list}) 24 25 26 def edit(request): 27 ''' 28 编辑 29 ''' 30 if request.method == 'POST': 31 id = request.POST.get('id') 32 name = request.POST.get('name') 33 press_id = request.POST.get('press_id') 34 obj = models.Book.objects.get(id=id) 35 obj.name = name 36 obj.press_id = press_id 37 obj.save() 38 return redirect('/list_book/') 39 id = request.GET.get('id') 40 obj = models.Book.objects.get(id=id) 41 press_list = models.Press.objects.all() 42 return render(request, 'book/edit.html', {'book': obj, 'press_list': press_list}) 43 44 45 def delete(request): 46 ''' 47 删除 48 ''' 49 id = request.GET.get('id') 50 models.Book.objects.get(id=id).delete() 51 return redirect('/list_book/')
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>添加书籍</title> 6 </head> 7 <body> 8 <form action="/add_book/" method="post"> 9 <p>名称:<input name="name" type="text"></p> 10 <p>出版社: <select name="press_id" > 11 {% for press in press_list %} 12 <option value="{{ press.id }}">{{ press.name }}</option> 13 {% endfor %} 14 </select></p> 15 <p><input type="submit" value="提交"></p> 16 </form> 17 </body> 18 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>书籍列表</title> 6 </head> 7 <body> 8 <a href="/add_book/">添加</a> 9 <table border="1" style="border-collapse:collapse;"> 10 <tr> 11 <td>序号</td> 12 <td>名称</td> 13 <td>出版社</td> 14 <td colspan="2">操作</td> 15 </tr> 16 {% for book in list %} 17 <tr> 18 <td>{{ forloop.counter }}</td> 19 <td>{{ book.name }}</td> 20 <td>{{ book.press.name }}</td> 21 <td><a href="/edit_book/?id={{ book.id }}">编辑</a></td> 22 <td><a href="/del_book/?id={{ book.id }}">删除</a></td> 23 </tr> 24 {% endfor %} 25 </table> 26 </body> 27 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>修改书籍</title> 6 </head> 7 <body> 8 <form action="/edit_book/" method="post"> 9 <input type="hidden" name="id" value="{{ book.id }}"> 10 <p>名称:<input name="name" type="text" value="{{ book.name }}"></p> 11 <p>出版社: 12 <select name="press_id"> 13 {% for press in press_list %} 14 {% if book.press.id == press.id %} 15 <option selected value="{{ press.id }}">{{ press.name }}</option> 16 {% else %} 17 <option value="{{ press.id }}">{{ press.name }}</option> 18 {% endif %} 19 {% endfor %} 20 </select> 21 </p> 22 <p><input type="submit" value="提交"></p> 23 </form> 24 </body> 25 </html>
-
作者(多对多)
1 from django.shortcuts import render, HttpResponse, redirect 2 from bookapp import models 3 4 5 def add(request): 6 ''' 7 添加 8 ''' 9 if request.method == 'POST': 10 book_id_list = request.POST.getlist('book_id_list') 11 print(book_id_list) 12 name = request.POST.get('name') 13 author = models.Author.objects.create(name=name) 14 author.book = book_id_list 15 author.save() 16 return redirect('/list_author/') 17 book_list = models.Book.objects.all() 18 return render(request, 'author/add.html', {'book_list': book_list}) 19 20 21 def list(request): 22 ''' 23 列表 24 ''' 25 all_list = models.Author.objects.all() 26 return render(request, 'author/list.html', {'list': all_list}) 27 28 29 def edit(request): 30 ''' 31 编辑 32 ''' 33 if request.method == 'POST': 34 id = request.POST.get('id') 35 name = request.POST.get('name') 36 book_id_list = request.POST.getlist('book_id_list') 37 obj = models.Author.objects.get(id=id) 38 obj.name = name 39 obj.book = book_id_list 40 obj.save() 41 return redirect('/list_author/') 42 id = request.GET.get('id') 43 obj = models.Author.objects.get(id=id) 44 book_list = models.Book.objects.all() 45 return render(request, 'author/edit.html', {'author': obj, 'book_list': book_list}) 46 47 48 def delete(request): 49 ''' 50 删除 51 ''' 52 id = request.GET.get('id') 53 models.Author.objects.get(id=id).delete() 54 return redirect('/list_author/')
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>添加作者</title> 6 </head> 7 <body> 8 <form action="/add_author/" method="post"> 9 <p>姓名:<input name="name" type="text"></p> 10 <p>拥有书籍: <select name="book_id_list" multiple> 11 {% for book in book_list %} 12 <option value="{{ book.id }}">{{ book.name }}</option> 13 {% endfor %} 14 </select></p> 15 <p><input type="submit" value="提交"></p> 16 </form> 17 </body> 18 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>作者列表</title> 6 </head> 7 <body> 8 <a href="/add_author/">添加</a> 9 <table border="1" style="border-collapse:collapse;"> 10 <tr> 11 <td>序号</td> 12 <td>姓名</td> 13 <td>拥有书籍</td> 14 <td colspan="2">操作</td> 15 </tr> 16 {% for author in list %} 17 <tr> 18 <td>{{ forloop.counter }}</td> 19 <td>{{ author.name }}</td> 20 <td>{% for book in author.book.all %} 21 {% if forloop.counter == author.book.count %} 22 {{ book.name }} 23 {% else %} 24 {{ book.name }}, 25 {% endif %} 26 {% endfor %} 27 </td> 28 <td><a href="/edit_author/?id={{ author.id }}">编辑</a></td> 29 <td><a href="/del_author/?id={{ author.id }}">删除</a></td> 30 </tr> 31 {% endfor %} 32 </table> 33 </body> 34 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>修改作者</title> 6 </head> 7 <body> 8 <form action="/edit_author/" method="post"> 9 <input type="hidden" name="id" value="{{ author.id }}"> 10 <p>姓名:<input name="name" type="text" value="{{ author.name }}"></p> 11 <p>拥有书籍: 12 <select name="book_id_list" multiple> 13 {% for book in book_list %} 14 {% if book in author.book.all %} 15 <option selected value="{{ book.id }}">{{ book.name }}</option> 16 {% else %} 17 <option value="{{ book.id }}">{{ book.name }}</option> 18 {% endif %} 19 {% endfor %} 20 </select> 21 </p> 22 <p><input type="submit" value="提交"></p> 23 </form> 24 </body> 25 </html>
配置路由
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from django.shortcuts import render, HttpResponse, redirect 2 from bookapp.service import press 3 from bookapp.service import book 4 from bookapp.service import author
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from django.conf.urls import url 2 from django.contrib import admin 3 4 from django.conf.urls import url 5 from bookapp import views 6 urlpatterns = [ 7 url(r'^add_press/', views.press.add), 8 url(r'^list_press/', views.press.list), 9 url(r'^edit_press/', views.press.edit), 10 url(r'^del_press/', views.press.delete), 11 url(r'^add_book/', views.book.add), 12 url(r'^list_book/', views.book.list), 13 url(r'^edit_book/', views.book.edit), 14 url(r'^del_book/', views.book.delete), 15 url(r'^add_author/', views.author.add), 16 url(r'^list_author/', views.author.list), 17 url(r'^edit_author/', views.author.edit), 18 url(r'^del_author/', views.author.delete), 19 ]
Java博客目录 | Python博客目录 | C#博客目录