Python - Django - ORM 实例(二)

在 app01/models.py 中添加 Book 类对象表

from django.db import models

# Create your models here.

# 出版社
class Publisher(models.Model):
    id = models.AutoField(primary_key=True)  # 自增的 ID 主键
    # 创建一个 varchar(64) 的唯一的不为空的字段
    name = models.CharField(max_length=64, null=False, unique=True)

# 书籍
class Book(models.Model):
    id = models.AutoField(primary_key=True)  # 自增的 ID 主键
    # 创建一个 varchar(64) 的唯一的不为空的字段
    title = models.CharField(max_length=64, null=False, unique=True)
    # 和出版社关联的外键字段
    publisher = models.ForeignKey(to="Publisher")

然后执行命令更新到数据库中

[email protected] > makemigrations
[email protected] > migrate

在 Book 表中添加 3 条数据

展示书籍列表:

创建 book_list.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>书籍列表</title>
</head>
<body>

<table border="1">
    <thead>
    <tr>
        <th>id</th>
        <th>书名</th>
        <th>出版社</th>
    </tr>
    </thead>
    <tbody>
    {% for book in book_list %}
        <tr>
        <td>{{ book.id }}</td>
        <td>{{ book.title }}</td>
        <td>{{ book.publisher.name }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>
</body>
</html>

这里的 book.publisher 获取到的是 Publisher 对象,因为 publisher 关联了 Publisher 对象

在 app01/views.py 中添加 book_list 函数

from django.shortcuts import render, redirect, HttpResponse
from app01 import models

# 展示出版社列表
def publisher_list(request):
    # 去数据库查出所有的出版社,填充到 html 中,返回给用户
    ret = models.Publisher.objects.all().order_by("id")  # order_by("id") 通过 id 进行排序
    return render(request, "publisher_list.html", {"publisher_list": ret})

# 添加新的出版社
def add_publisher(request):
    # 如果是 POST 请求,就获取用户填写的数据
    if request.method == "POST":
        new_publisher = request.POST.get("publisher_name")
        # 获得数据后去数据库中新增一条数据
        models.Publisher.objects.create(name=new_publisher)
        # 添加成功后进行跳转
        return redirect("/publisher_list/")

    # 用户来到该界面返回的 html 页面
    return render(request, "add_publisher.html")

# 删除出版社
def del_publisher(request):
    # 从 GET 请求的参数中拿到要删除的 id 值
    del_id = request.GET.get(‘id‘)
    # 如果取到 id 值,就去数据库中删除该 id 的数据
    if del_id:
        # 根据 id 查找数据,并删除
        del_obj = models.Publisher.objects.get(id=del_id).delete()
        # 删除后返回页面
        return redirect("/publisher_list/")
    else:
        return HttpResponse("要删除的数据不存在!")

# 编辑出版社
def edit_publisher(request):
    # 获取 POST 发来的数据,并更新到数据库中
    if request.method == "POST":
        # 获取 POST 传送来的 id 值和出版社
        edit_id = request.POST.get(‘id‘)
        new_name = request.POST.get(‘publisher_name‘)
        # 根据 id 取得出版社
        publisher = models.Publisher.objects.get(id=edit_id)
        publisher.name = new_name
        publisher.save()  # 把修改的结果提交到数据库
        return redirect("/publisher_list/")  # 跳转到列表页面

    # 从 GET 请求中取得 id 值
    publisher_id = request.GET.get(‘id‘)
    if publisher_id:
        # 获取当前编辑的出版社对象
        publisher_obj = models.Publisher.objects.get(id=publisher_id)
        return render(request, "edit_publisher.html", {"publisher": publisher_obj})
    else:
        return HttpResponse("编辑的出版社不存在!")

# 展示书籍列表
def book_list(request):
    # 去数据库中查询所有书籍
    all_book = models.Book.objects.all()
    # 渲染数据
    return render(request, "book_list.html", {"book_list": all_book})

在 mysite0/urls.py 中添加对应关系

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r‘^publisher_list/‘, views.publisher_list),
    url(r‘^add_publisher/‘, views.add_publisher),
    url(r‘^del_publisher/‘, views.del_publisher),
    url(r‘^edit_publisher/‘, views.edit_publisher),
    url(r‘^book_list/‘, views.book_list),
]

运行结果:

添加书籍:

修改 book_list.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>书籍列表</title>
</head>
<body>

<table border="1">
    <thead>
    <tr>
        <th>id</th>
        <th>书名</th>
        <th>出版社</th>
    </tr>
    </thead>
    <tbody>
    {% for book in book_list %}
        <tr>
        <td>{{ book.id }}</td>
        <td>{{ book.title }}</td>
        <td>{{ book.publisher.name }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

<a href="/add_book/">添加书籍</a>

</body>
</html>

创建 add_book.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加书籍</title>
</head>
<body>

<h1>添加书籍</h1>

<form action="/add_book/" method="post">
    <p>
        书名:<input type="text" name="book_title">
    </p>
    <p>
        出版社:
        <select name="publisher" >
            {% for publisher in publisher_list %}
                <option value="{{ publisher.id }}">{{ publisher.name }}</option>
            {% endfor %}
        </select>
    </p>
    <p>
         <input type="submit" value="提交">
    </p>

</form>

</body>
</html>

在 app01/views.py 中添加 add_book 函数

from django.shortcuts import render, redirect, HttpResponse
from app01 import models

# 展示出版社列表
def publisher_list(request):
    # 去数据库查出所有的出版社,填充到 html 中,返回给用户
    ret = models.Publisher.objects.all().order_by("id")  # order_by("id") 通过 id 进行排序
    return render(request, "publisher_list.html", {"publisher_list": ret})

# 添加新的出版社
def add_publisher(request):
    # 如果是 POST 请求,就获取用户填写的数据
    if request.method == "POST":
        new_publisher = request.POST.get("publisher_name")
        # 获得数据后去数据库中新增一条数据
        models.Publisher.objects.create(name=new_publisher)
        # 添加成功后进行跳转
        return redirect("/publisher_list/")

    # 用户来到该界面返回的 html 页面
    return render(request, "add_publisher.html")

# 删除出版社
def del_publisher(request):
    # 从 GET 请求的参数中拿到要删除的 id 值
    del_id = request.GET.get(‘id‘)
    # 如果取到 id 值,就去数据库中删除该 id 的数据
    if del_id:
        # 根据 id 查找数据,并删除
        del_obj = models.Publisher.objects.get(id=del_id).delete()
        # 删除后返回页面
        return redirect("/publisher_list/")
    else:
        return HttpResponse("要删除的数据不存在!")

# 编辑出版社
def edit_publisher(request):
    # 获取 POST 发来的数据,并更新到数据库中
    if request.method == "POST":
        # 获取 POST 传送来的 id 值和出版社
        edit_id = request.POST.get(‘id‘)
        new_name = request.POST.get(‘publisher_name‘)
        # 根据 id 取得出版社
        publisher = models.Publisher.objects.get(id=edit_id)
        publisher.name = new_name
        publisher.save()  # 把修改的结果提交到数据库
        return redirect("/publisher_list/")  # 跳转到列表页面

    # 从 GET 请求中取得 id 值
    publisher_id = request.GET.get(‘id‘)
    if publisher_id:
        # 获取当前编辑的出版社对象
        publisher_obj = models.Publisher.objects.get(id=publisher_id)
        return render(request, "edit_publisher.html", {"publisher": publisher_obj})
    else:
        return HttpResponse("编辑的出版社不存在!")

# 展示书籍列表
def book_list(request):
    # 去数据库中查询所有书籍
    all_book = models.Book.objects.all()
    print(all_book)
    # 渲染数据
    return render(request, "book_list.html", {"book_list": all_book})

# 添加书籍
def add_book(request):
    if request.method == "POST":
        new_title = request.POST.get("book_title")
        new_publisher_id = request.POST.get("publisher")
        # 去数据库中创建数据
        models.Book.objects.create(title=new_title, publisher_id=new_publisher_id)
        return redirect("/book_list/")
    # 去数据库取得出版社数据展示在页面上以供用户选择
    publishers = models.Publisher.objects.all()
    return render(request, "add_book.html", {"publisher_list": publishers})

在 mysite0/urls.py 中添加对应关系

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^publisher_list/‘, views.publisher_list),
    url(r‘^add_publisher/‘, views.add_publisher),
    url(r‘^del_publisher/‘, views.del_publisher),
    url(r‘^edit_publisher/‘, views.edit_publisher),
    url(r‘^book_list/‘, views.book_list),
    url(r‘^add_book/‘, views.add_book),
]

运行结果:

点击“添加书籍”

点击“提交”

删除书籍:

修改 book_list.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>书籍列表</title>
</head>
<body>

<table border="1">
    <thead>
    <tr>
        <th>id</th>
        <th>书名</th>
        <th>出版社</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    {% for book in book_list %}
        <tr>
        <td>{{ book.id }}</td>
        <td>{{ book.title }}</td>
        <td>{{ book.publisher.name }}</td>
        <td>
            <a href="/del_book/?id={{ book.id }}">删除</a>
        </td>
        </tr>
    {% endfor %}
    </tbody>
</table>

<a href="/add_book/">添加书籍</a>

</body>
</html>

在 app01/views.py 中添加 del_book 函数

from django.shortcuts import render, redirect, HttpResponse
from app01 import models

# 展示出版社列表
def publisher_list(request):
    # 去数据库查出所有的出版社,填充到 html 中,返回给用户
    ret = models.Publisher.objects.all().order_by("id")  # order_by("id") 通过 id 进行排序
    return render(request, "publisher_list.html", {"publisher_list": ret})

# 添加新的出版社
def add_publisher(request):
    # 如果是 POST 请求,就获取用户填写的数据
    if request.method == "POST":
        new_publisher = request.POST.get("publisher_name")
        # 获得数据后去数据库中新增一条数据
        models.Publisher.objects.create(name=new_publisher)
        # 添加成功后进行跳转
        return redirect("/publisher_list/")

    # 用户来到该界面返回的 html 页面
    return render(request, "add_publisher.html")

# 删除出版社
def del_publisher(request):
    # 从 GET 请求的参数中拿到要删除的 id 值
    del_id = request.GET.get(‘id‘)
    # 如果取到 id 值,就去数据库中删除该 id 的数据
    if del_id:
        # 根据 id 查找数据,并删除
        del_obj = models.Publisher.objects.get(id=del_id).delete()
        # 删除后返回页面
        return redirect("/publisher_list/")
    else:
        return HttpResponse("要删除的数据不存在!")

# 编辑出版社
def edit_publisher(request):
    # 获取 POST 发来的数据,并更新到数据库中
    if request.method == "POST":
        # 获取 POST 传送来的 id 值和出版社
        edit_id = request.POST.get(‘id‘)
        new_name = request.POST.get(‘publisher_name‘)
        # 根据 id 取得出版社
        publisher = models.Publisher.objects.get(id=edit_id)
        publisher.name = new_name
        publisher.save()  # 把修改的结果提交到数据库
        return redirect("/publisher_list/")  # 跳转到列表页面

    # 从 GET 请求中取得 id 值
    publisher_id = request.GET.get(‘id‘)
    if publisher_id:
        # 获取当前编辑的出版社对象
        publisher_obj = models.Publisher.objects.get(id=publisher_id)
        return render(request, "edit_publisher.html", {"publisher": publisher_obj})
    else:
        return HttpResponse("编辑的出版社不存在!")

# 展示书籍列表
def book_list(request):
    # 去数据库中查询所有书籍
    all_book = models.Book.objects.all()
    print(all_book)
    # 渲染数据
    return render(request, "book_list.html", {"book_list": all_book})

# 添加书籍
def add_book(request):
    if request.method == "POST":
        new_title = request.POST.get("book_title")
        new_publisher_id = request.POST.get("publisher")
        # 去数据库中创建数据
        models.Book.objects.create(title=new_title, publisher_id=new_publisher_id)
        return redirect("/book_list/")
    # 去数据库取得出版社数据展示在页面上以供用户选择
    publishers = models.Publisher.objects.all()
    return render(request, "add_book.html", {"publisher_list": publishers})

# 删除书籍
def del_book(request):
    # 从 URL 中获取要删除的书籍的 id
    del_id = request.GET.get("id")
    # 去数据库中删除指定 id 的书籍
    models.Book.objects.get(id=del_id).delete()
    # 跳转到书籍列表页面
    return redirect("/book_list/")

在 mysite0/urls.py 中添加对应关系

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^publisher_list/‘, views.publisher_list),
    url(r‘^add_publisher/‘, views.add_publisher),
    url(r‘^del_publisher/‘, views.del_publisher),
    url(r‘^edit_publisher/‘, views.edit_publisher),
    url(r‘^book_list/‘, views.book_list),
    url(r‘^add_book/‘, views.add_book),
    url(r‘^del_book/‘, views.del_book),
]

运行结果:

删除“PHP”

页面闪了一下,PHP 就被删除了

原文地址:https://www.cnblogs.com/sch01ar/p/10771707.html

时间: 2024-08-30 15:13:03

Python - Django - ORM 实例(二)的相关文章

Nginx + uWSGI + Python + Django部署实例

Nginx: Nginx 是一个高性能的 Web 和反向代理服务器, 它具有有很多非常优越的特性: 作为 Web 服务器:相比 Apache,Nginx 使用更少的资源,支持更多的并发连接,体现更高的效率,这点使 Nginx 尤其受到虚拟主机提供商的欢迎.能够支持高达 50,000 个并发连接数的响应,感谢 Nginx 为我们选择了 epoll and kqueue 作为开发模型. 作为负载均衡服务器:Nginx 既可以在内部直接支持 Rails 和 PHP,也可以支持作为 HTTP代理服务器

Python - Django - ORM 查询方法

models.py: from django.db import models class Human(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() birthday = models.DateField(auto_now_add=True) 在数据库中添加几条数据 在 Python 脚本中调用 Dj

Python - Django - ORM QuerySet 方法补充

models.py: from django.db import models class Employee2(models.Model): name = models.CharField(max_length=16) age = models.IntegerField() salary = models.IntegerField() province = models.CharField(max_length=32) dept = models.ForeignKey(to="Dept"

Python - Django - ORM 分组查询补充

单表查询: models.py: from django.db import models class Employee(models.Model): name = models.CharField(max_length=16) age = models.IntegerField() salary = models.IntegerField() province = models.CharField(max_length=32) dept = models.CharField(max_lengt

Python/Django(CBA/FBA/ORM操作)

Python/Django(CBA/FBA/ORM操作) CBA:url对应的类(模式) 1 ##====================================CBA操作============================ 2 3 # class geting(View): 4 # def dispatch(self, request, *args, **kwargs): 5 # print('before') 6 # obj = super(geting,self).dispat

python 之 Django框架(orm单表查询、orm多表查询、聚合查询、分组查询、F查询、 Q查询、事务、Django ORM执行原生SQL)

12.329 orm单表查询 import os if __name__ == '__main__': # 指定当前py脚本需要加载的Django项目配置信息 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "orm_demo.settings") import django django.setup() # 启动Django项目 from app01 import models #返回QuerySet对象的方法: r

数据库表反向生成(二)django ORM inspectdb

在前一篇我们说了,mybatis-generator反向生成代码. 这里我们开始说如何在django中反向生成mysql model代码. 我们在展示django ORM反向生成之前,我们先说一下怎么样正向生成代码. 正向生成,指的是先创建model.py文件,然后通过django内置的编译器,在数据库如mysql中创建出符合model.py的表. 反向生成,指的是先在数据库中create table,然后通过django内置的编译器,生成model代码. 1.准备工作 创建django工程以及

二、Python Django的URL设置

Python Django的URL设置 一.url使用方式 1.正则表达方式: url(r'^blog/index/$','blog.views.index'), 2.导入的方式: from blog.views import index ..... url(r'^blog/index/$',index), ..... 3. urlpatterns = patterns('blog.views', url(r'^blog/index/$','index'), ) 二.URL参数传递给index

python day-76 django orm 查询链表

一.基于双下划线跨表查询(join查询) 在上一篇中,我们简单的介绍了基于对象的跨表查询,本章将继续阐述基于双下划线的跨表查询,所用的表格均为上章中所创建的表格.    ##########################基于双下划线的查询:正向查询,按字段,反向查询,按表名##################### 1.一对多 实例一(正向,用字段): # 查询红楼梦的出版社名称 #方式1: ret=Book.objects.filter(title="红楼梦").values(&q