文档章节

python框架之Django(2)-简单的CRUD

o
 osc_x4h57ch8
发布于 2018/04/20 16:40
字数 1914
阅读 0
收藏 0
def

精选30+云产品,助力企业轻松上云!>>>

写一个简单的项目小例子来了解Django中的O/RM操作

前戏

创建app

#在Django项目根目录下执行
python3 manage.py startapp [app name]

配置数据库连接信息

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # 连接的数据库类型
        'HOST': '127.0.0.1',  # 连接数据库的地址
        'PORT': 3306,  # 端口
        'NAME': "testdb",  # 数据库名称
        'USER': 'root',  # 用户
        'PASSWORD': 'root'  # 密码
    }
}
/[project name]/settings.py->DATABASES节

让Django用pymysql来代替默认的MySQLdb

import pymysql
pymysql.install_as_MySQLdb()
/[project name]/__init__.py

让项目'知道'APP

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'login_app.apps.LoginAppConfig'
]
/[project name]/settings.py->INSTALLED_APPS节

表关系

代码

创建模型

在app下面的models.py文件中定义类,这些类必须继承models.Model

 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)
/[app name]/models.py

执行命令

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/')
    /[app name]/service/press.py
     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>
    /templates/press/add.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>
    /templates/press/list.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>
    /templates/press/edit.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/')
    /[app name]/service/book.py
     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>
    /templates/book/add.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>
    /templates/book/list.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>
    /templates/book/edit.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/')
    /[app name]/service/author.py
     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>
    /templates/author/add.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>
    /templates/author/list.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>
    /templates/author/edit.html 编辑作者页

配置路由

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
/[app name]/views.py
 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 ]
/[project name]/urls.py

点击下载完整示例

o
粉丝 0
博文 500
码字总数 0
作品 0
私信 提问
加载中
请先登录后再评论。

暂无文章

敖丙20 张图揭开内存管理的迷雾

前言 之前有不少读者跟我反馈,能不能写图解操作系统? 既然那么多读者想看,我最近就在疯狂的复习操作系统的知识。 操作系统确实是比较难啃的一门课,至少我认为比计算机网络难太多了,但它...

敖丙
07/02
11
0
拉勾网拉你上勾

预览 需求简介 拉勾网是一个互联网行业的一个招聘网站,上面有许多职位,于是乎,小编想提取指定职位的基本信息(职位名,薪水,工作经验,工作地点,教育背景),然后插入 MongoDB 数据库,...

木下瞳
2019/04/17
20
0
我是一个线程(第一人称)

来源 | 转自 码农翻身 作者 | 刘欣 全文总共 | 4600 字 预计阅读时间 | 12 分钟 第一回 初生牛犊 我是一个线程,我一出生就被编了个号:0x3704,然后被领到一个昏暗的屋子里,在这里我发现了...

geniusian
2019/11/04
16
0
SkyWalking 权限认证

版本:7.0.0 描述 为了数据传输安全,确保网络连接是安全的。采用 Token 认证确保采集的应用数据是被信任的。 当前版本,仅支持简单的字符串 Token 配置 代理端配置文件agent.config设置 # ...

zm123321
32分钟前
17
0
是否允许实体正文进行HTTP DELETE请求? - Is an entity body allowed for an HTTP DELETE request?

问题: When issuing an HTTP DELETE request, the request URI should completely identify the resource to delete. 发出HTTP DELETE请求时,请求URI应该完全标识要删除的资源。 However,......

javail
昨天
27
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部