models.py

from django.db import models

# Create your models here.
class Author(models.Model):
nid = models.AutoField(primary_key=True)
name=models.CharField( max_length=32)
age=models.IntegerField() class Publish(models.Model):
nid = models.AutoField(primary_key=True)
name=models.CharField( max_length=32)
city=models.CharField( max_length=32)
email=models.EmailField() class Book(models.Model): nid = models.AutoField(primary_key=True)
title = models.CharField( max_length=32)
publishDate=models.DateField()
price=models.DecimalField(max_digits=5,decimal_places=2) # 999.99 # 与Publish建立一对多的关系,外键字段建立在多的一方
publish=models.ForeignKey(to="Publish",to_field="nid",on_delete=models.CASCADE)
# 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表
authors=models.ManyToManyField(to='Author',)

urls.py

from django.contrib import admin
from django.urls import path,re_path from book import views urlpatterns = [
path('admin/', admin.site.urls),
re_path('books/add/$', views.add_book),
re_path('books/$', views.books),
re_path('books/(\d+)/change/$', views.change_book),
re_path('books/(\d+)/delete/$', views.delete_book),
]

在settings里边

views.py

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

from .models import Publish,Author,Book
def add_book(request): if request.method=="POST":
title=request.POST.get("title")
price=request.POST.get("price")
pub_date=request.POST.get("pub_date")
publish_id=request.POST.get("publish_id")
authors_id_list=request.POST.getlist("authors_id_list") # checkbox,select book_obj=Book.objects.create(title=title,price=price,publishDate=pub_date,publish_id=publish_id)
print(authors_id_list) # ['2', '3'] book_obj.authors.add(*authors_id_list) return HttpResponse("success") publish_list=Publish.objects.all()
author_list=Author.objects.all() return render(request,"addbook.html",{"author_list":author_list,"publish_list":publish_list}) def books(request):
book_list = Book.objects.all()
return render(request, "book.html",{"book_list":book_list}) def change_book(request,edit_book_id):
edit_book_obj = Book.objects.filter(pk = edit_book_id).first()
if request.method == 'POST':
title = request.POST.get('title')
price = request.POST.get('price')
pub_date = request.POST.get('pub_date')
publish_id = request.POST.get('publish_id')
authors_id_list = request.POST.getlist('authors_id_list') Book.objects.filter(pk=edit_book_id).update(title=title, price=price,publishDate=pub_date, publish_id=publish_id)
# edit_book_obj.authors.clear()
# edit_book_obj.authors.add(*authors_id_list)
edit_book_obj.authors.set(authors_id_list) return redirect("/books/") publish_list = Publish.objects.all()
author_list = Author.objects.all() return render(request, 'editbook.html',{"edit_book_obj":edit_book_obj, "publish_list":publish_list, "author_list":author_list}) def delete_book(request, delete_book_id):
Book.objects.filter(pk=delete_book_id).delete()
return redirect("/books/")

addbook.html(添加书籍)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bs/css/bootstrap.css">
</head>
<body> <h3>添加书籍</h3> <div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="" method="post">
{% csrf_token %}
<div class="form-group">
<label for="">名称</label>
<input type="text" name="title" class="form-control" value="">
</div> <div class="form-group">
<label for="">价格</label>
<input type="text" name="price" class="form-control">
</div> <div class="form-group">
<label for="">出版日期</label>
<input type="date" name="pub_date" class="form-control">
</div> <div class="form-group">
<label for="">出版社</label>
<select name="publish_id" id="" class="form-control">
{% for publish in publish_list %}
<option value="{{ publish.pk }}">{{ publish.name }}</option>
{% endfor %}
</select>
</div> <div class="form-group">
<label for="">作者</label>
<select type="text" name="authors_id_list" multiple class="form-control">
{% for author in author_list %}
<option value="{{ author.pk }}">{{ author.name }}</option>
{% endfor %} </select>
</div>
<input type="submit" class="btn btn-default"> </form>
</div>
</div>
</div> </body>
</html>

book.html(查看书籍)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bs/css/bootstrap.css">
</head>
<body> <h3>查看书籍</h3> <div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2"> {# 边框、悬浮时变色、条纹编码 #}
<a href="/books/add" class="btn btn-primary">添加书籍</a>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>编号</th>
<th>书籍名称</th>
<th>价格</th>
<th>出版日期
<th>出版社</th>
<th>作者</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for book in book_list %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ book.title }}</td>
<td>{{ book.price }}</td>
<td>{{ book.publishDate|date:'Y-m-d' }}</td>
<td>{{ book.publish.name }}</td>
<td>
{% for author in book.authors.all %}
{% if forloop.last %}
<span>{{ author.name }}</span>
{% else %}
<span>{{ author.name }}</span>,
{% endif %}
{% endfor %} </td>
<td>
<a href="/books/{{ book.pk }}/change/" class="btn btn-warning">编辑</a>
<a href="/books/{{ book.pk }}/delete/" class="btn btn-danger">删除</a> </td>
</tr>
{% endfor %} </tbody>
</table>
</div>
</div>
</div> </body>
</html>

editbook.html(编辑书籍)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bs/css/bootstrap.css">
</head>
<body> <h3>编辑书籍</h3> <div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="" method="post">
{% csrf_token %}
<div class="form-group">
<label for="">名称</label>
<input type="text" name="title" class="form-control" value="{{ edit_book_obj.title }}">
</div> <div class="form-group">
<label for="">价格</label>
<input type="text" name="price" class="form-control" value="{{ edit_book_obj.price }}">
</div> <div class="form-group">
<label for="">出版日期</label>
<input type="date" name="pub_date" class="form-control"
value="{{ edit_book_obj.publishDate|date:'Y-m-d' }}">
</div> <div class="form-group">
<label for="">出版社</label>
<select name="publish_id" id="" class="form-control">
{% for publish in publish_list %}
<option selected value="{{ publish.pk }}">{{ publish.name }}</option>
{% if edit_book_obj.publish == publish %}
{% else %}
<option value="{{ publish.pk }}">{{ publish.name }}</option>
{% endif %} {% endfor %}
</select>
</div> <div class="form-group">
<label for="">作者</label>
<select type="text" name="authors_id_list" multiple class="form-control">
{% for author in author_list %}
{% if author in edit_book_obj.authors.all %}
<option selected value="{{ author.pk }}">{{ author.name }}</option>
{% else %}
<option value="{{ author.pk }}">{{ author.name }}</option>
{% endif %}
{% endfor %} </select>
</div>
<input type="submit" class="btn btn-default"> </form>
</div>
</div>
</div> </body>
</html>

练习|Django-多表的更多相关文章

  1. python运维开发(十九)----Django后台表单验证、session、cookie、model操作

    内容目录: Django后台表单验证 CSRF加密传输 session.cookie model数据库操作 Django后台Form表单验证 Django中Form一般有2种功能: 1.用于做用户提交 ...

  2. django form表单验证

    一. django form表单验证引入 有时时候我们需要使用get,post,put等方式在前台HTML页面提交一些数据到后台处理例 ; <!DOCTYPE html> <html ...

  3. django from表单验证

    django from表单验证   实现:表单验证 工程示例: urls.py 1 2 3 4 5 6 7 8 9 from django.conf.urls import url from djan ...

  4. Django 数据表更改

    Django 数据表更改 « Django 开发内容管理系统(第四天) Django 后台 » 我们设计数据库的时候,早期设计完后,后期会发现不完善,要对数据表进行更改,这时候就要用到本节的知识. D ...

  5. python 全栈开发,Day73(django多表添加,基于对象的跨表查询)

    昨日内容回顾 多表方案: 如何确定表关系呢? 表关系是在2张表之间建立的,没有超过2个表的情况. 那么相互之间有2条关系线,先来判断一对多的关系. 如果其中一张表的记录能够对应另外一张表的多条记录,那 ...

  6. python 全栈开发,Day72(昨日作业讲解,昨日内容回顾,Django多表创建)

    昨日作业讲解 1.图书管理系统 实现功能:book单表的增删改查 1.1 新建一个项目bms,创建应用book.过程略... 1.2 手动创建static目录,并在目录里面创建css文件夹,修改set ...

  7. Django:表结构发生变化需要执行命令

    Django:表结构发生变化需要执行命令 Django:表结构发生变化需要执行命令 mysite> python manage.py makemigrations blog #让 Django ...

  8. django Form表单的使用

    Form django表单系统中,所有的表单类都作为django.forms.Form的子类创建,包括ModelForm 关于django的表单系统,主要分两种 基于django.forms.Form ...

  9. Django(5) session登录注销、csrf及中间件自定义、django Form表单验证(非常好用)

    一.Django中默认支持Session,其内部提供了5种类型的Session供开发者使用: 数据库(默认) 缓存 文件 缓存+数据库 加密cookie 1.数据库Session 1 2 3 4 5 ...

  10. django删除表重建&修改用户密码&base64加密解密字符串&ps aux参数说明&各种Error例子

    1.django的queryset不支持负索引 AssertionError: Negative indexing is not supported. 2.django向前端JavaScript传递列 ...

随机推荐

  1. 八、uboot 代码流程分析---board_init_f

    接着上一节,板子开始做前期初始化工作. 8.1 board_init_f Board_f.c (common) /* 板子初次初始化.boot_flags = 0 */ void board_init ...

  2. cdh部署

    supermicro安装环境 本次安装基于无因特网的环境,共安装2个节点(一个master节点,一个data及节点),所用系统为centos7.x,所有安装过程均使用root用户.具体的节点信息如下: ...

  3. 解决 ionic 中的 CORS(跨域)

    译者注:本人翻译功力有限,所以文中难免有翻译不准确的地方,凑合看吧,牛逼的话你看英文版的去,完事儿欢迎回来指正交流(^_^) 如果你通过 ionic serve 或者 ionic run 命令使用或 ...

  4. 无责任共享 Coursera、Udacity 等课程视频(转载)

    转载链接:https://www.zybuluo.com/illuz/note/71868 B站计划:https://www.zybuluo.com/illuz/note/832995#cs基础课程

  5. 从Linux内核中获取真随机数【转】

    转自:http://www.cnblogs.com/bigship/archive/2010/04/04/1704228.html 内核随机数产生器 Linux内核实现了一个随机数产生器,从理论上说这 ...

  6. linux系统下安装redis及配置

    下载Redis redis-3.2.11.tar.gz 解压编译 tar xzf redis-3.2.11.tar.gz cd redis-3.2.11 make 编译完成之后,可以看到解压文件red ...

  7. tomcat jsp页面乱码解决

    浏览器接收服务器响应的中文参数: JSP页面中告诉浏览器使用什么编码: <%@ page language="java" contentType="text/htm ...

  8. KVM -> 虚拟机管理&console登录_02

    1.KVM虚拟机管理操作 virsh命令常用参数总结 1.开机关机: virsh list (只可以查看运行的虚拟机) virsh list  --all (全部都可以查看) 开机与关机: virsh ...

  9. PYTHON-文件指针的移动,移动和函数基础

    # 文件内指针的移动 #大前提:文件内指针的移动是Bytes为单位的,唯独t模式下的read读取内容个数是以字符为单位 # f.seek(指针移动的字节数,模式控制): 控制文件指针的移动# 模式控制 ...

  10. flask的orm框架(SQLAlchemy)-一对多查询以及多对多查询

    一对多,多对多是什么? 一对多.例如,班级与学生,一个班级对应多个学生,或者多个学生对应一个班级. 多对多.例如,学生与课程,可以有多个学生修同一门课,同时,一门课也有很多学生. 一对多查询 如果一个 ...