1.外键相关

  一对多的概念 ,这里是一个出版社对应本书籍 ! 设计表使用model

  models.ForeignKey('关联一', on_delete=models.CASCADE)          #给多设置外键 ,关联一 ,设置级联删除当一的内容被删除 ,所关联的多都被删除

from django.db import models

# Create your models here.
class presslist(models.Model):
name = models.CharField(max_length=32) def __str__(self):
return self.name class Book(models.Model):
name = models.CharField(max_length=32)
p_id = models.ForeignKey('presslist', on_delete=models.CASCADE)

2.urls.py代码

  两套增删改查

from django.conf.urls import url
from app1 import views urlpatterns = [
url(r'^press/list/', views.presslist, name='presslist'),
url(r'^press/del/(\d+)/', views.pressdel, name='pressdel'),
url(r'^press/add/', views.pressadd, name='pressadd'),
url(r'^press/edit/(?P<edit_id>\d+)/', views.pressedit1.as_view(), name='pressedit'), url(r'^book/list/', views.booklist, name='booklist'),
url(r'^book/del/(\d+)/', views.bookdel, name='bookdel'),
url(r'^book/add/', views.bookadd, name='bookadd'),
url(r'^book/edit/(\d+)/', views.bookedit, name='bookedit'), ]

3.views视图函数

  两套视图函数

  重点的 :models.Book.objects.create(name=book_name, p_id_id=press_id)  ,其中创建书籍记录需要关联出版社 ,这里面必须是从出版社表取数据p_id_id

from django.shortcuts import render, redirect, reverse, HttpResponse
from django.views import View
from app1 import models
import time
import functools
from django.utils.decorators import method_decorator # Create your views here. def presslist(request):
msg_all = models.presslist.objects.all()
return render(request, 'cbs.html', {'msg': msg_all}) def pressadd(request):
if request.method == 'POST':
press_name = request.POST.get('name')
models.presslist.objects.create(name=press_name)
return redirect(reverse('presslist'))
return render(request, 'cbsadd-edit.html') def pressdel(request, del_id):
print(del_id, type(del_id))
models.presslist.objects.get(pk=del_id).delete()
return redirect(reverse('presslist')) def pressedit(request, edit_id, test_id):
obj = models.presslist.objects.get(pk=edit_id)
print(test_id, edit_id)
msg = ''
if request.method == 'POST':
obj.name = request.POST.get('name') if models.presslist.objects.filter(name=obj.name):
msg = '已存在' if not obj.name:
msg = '不能为空' if not models.presslist.objects.filter(name=obj.name) and obj.name:
obj.save() return redirect(reverse('presslist'))
return render(request, 'cbsadd-edit.html', {'obj': obj, 'msg': msg}) class pressedit1(View): def get(self, request, edit_id, msg=''):
obj = models.presslist.objects.get(pk=edit_id)
return render(request, 'cbsadd-edit.html', {'obj': obj, 'msg': msg}) def post(self, request, edit_id):
msg = ''
obj = models.presslist.objects.get(pk=edit_id)
obj.name = request.POST.get('name')
if models.presslist.objects.filter(name=obj.name):
msg = '已存在'
if not obj.name:
msg = '不能为空'
if not models.presslist.objects.filter(name=obj.name) and obj.name:
obj.save()
return redirect(reverse('presslist'))
return self.get(request, edit_id, msg) def booklist(request):
msg_all = models.Book.objects.all()
return render(request, 'cbs.html', {'msg': msg_all}) def bookdel(request, del_id):
models.Book.objects.get(pk=del_id).delete()
return redirect(reverse('booklist')) def bookadd(request):
msg_all = models.presslist.objects.all()
if request.method == 'POST':
book_name = request.POST.get('name')
press_id = int(request.POST.get('pid'))
models.Book.objects.create(name=book_name, p_id_id=press_id)
return redirect(reverse('booklist'))
return render(request, 'cbsadd-edit.html', {'msg_all': msg_all}) def bookedit(request, edit_id):
obj = models.Book.objects.get(pk=edit_id)
msg = ''
if request.method == 'POST':
obj.name = request.POST.get('name') if models.Book.objects.filter(name=obj.name):
msg = '已存在' if not obj.name:
msg = '不能为空' if not models.Book.objects.filter(name=obj.name) and obj.name:
obj.save() return redirect(reverse('booklist'))
return render(request, 'cbsadd-edit.html', {'obj': obj, 'msg': msg})

4.模板复用

  cbs.html

###展示出版社 ,展示书籍列表的模板
{% extends 'base.html' %}
{% block body1 %}
<table class="text-center table table-striped table-bordered">
<tr>
<td>ID</td>
{% if msg.0.p_id %}
<td>书名</td>
<td>出版社名字</td>
{% else %}
<td>出版社名字</td>
{% endif %}
<td>操作</td>
</tr>
{% for obj in msg %}
<tr>
<td>{{ obj.pk }}</td>
<td>{{ obj.name }}</td>
{% if obj.p_id %}
<td>{{ obj.p_id.name }}</td>
<td><a href={% url 'bookedit' obj.pk %}><i class="fa fa-pencil-square-o" aria-hidden="true">&nbsp&nbsp&nbsp</i></a>
<a href={% url 'bookdel' obj.pk %}><i class="fa fa-remove" aria-hidden="true"></i></a></td>
{% else %}
<td><a href={% url 'pressedit' edit_id=obj.pk %}><i class="fa fa-pencil-square-o"
aria-hidden="true">&nbsp&nbsp&nbsp</i></a>
<a href={% url 'pressdel' obj.pk %}><i class="fa fa-remove" aria-hidden="true"></i></a></td>
{% endif %} </tr>
{% endfor %}
</table>
{% endblock %}

  cbsadd-edit.html

###修改与新增的复用模板
{% extends 'base.html' %} {% block body1 %}
<form action="" method="post">
<div style="margin-left: 100px;margin-top: 50px;" class="col-md-6 ">
<input type="text" class="form-control" name="name" placeholder="{{ obj.name }}">{{ msg }}
{% if msg_all %}
<select name="pid">
{% for obj in msg_all %}
<option value="{{ obj.pk }}">{{ obj.name }}</option>
{% endfor %}
</select>
{% endif %} </div>
<div style="margin-left: 10px;margin-top: 50px;" class="col-md-2 ">
<button type="submit" class="btn btn-primary">提交</button>
</div>
</form>
{% endblock %}

  

django5-书籍与出版社关联外键的更多相关文章

  1. SQL 关联外键报错类型不匹配

    如题,关联外键的时候,报错类型匹配.但是两个 类型都是int sql 如下: CREATE TABLE IF NOT EXISTS `alert_receiver_map` ( `id` INT UN ...

  2. hibernate-取消关联外键引用数据丢失抛异常的设置@NotFound

    hibernate项目里面配了很多many-to-one的关联,后台在查询数据时已经作了健全性判断,但还是经常抛出对象找不到异常: org.hibernate.ObjectNotFoundExcept ...

  3. Python-多表关联 外键 级联

    分表为什么分表 多表关联多表关系 ****** 表之间的关系 为什么要分表 多对一 一个外键 多对多 一个中间表 两个外键 一对一 一个外键加一个唯一约束外键约束 ****** foreign key ...

  4. jpa双向一对一关联外键映射

    项目结构: Wife package auth.model; import javax.persistence.CascadeType; import javax.persistence.Column ...

  5. hibernate 多表关联外键问题无法截断表的解决办法

    目前只有一个办法 就是手动清除其他表的外键关联,然后在做一个小swing单独去操作这个表,而不运行主控方相关的代码 当web运行后,外键会再次设置好

  6. UCML 参与者关键 与依赖关联外键

  7. hibernate中指定非外键进行关联

    /** * 上级资源 */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "PARENT_ID", reference ...

  8. sqlalchemy外键关联

    一.创建两张表,并关联外键 导入ForenginKey模块 # -*- coding: UTF-8 -*- from sqlalchemy import create_engine from sqla ...

  9. day08 外键字段的增删查改

    day08 外键字段的增删查改 今日内容概要 外键字段的增删查改 正反向查询的概念 基于对象的跨表查询(子查询) 基于双下划线的跨表查询(连表操作) 聚合查询与分组查询 F查询和Q查询 前提准备 cl ...

随机推荐

  1. SpringCloud微服务(07):Zipkin组件,实现请求链路追踪

    本文源码:GitHub·点这里 || GitEE·点这里 一.链路追踪简介 1.Sleuth组件简介 Sleuth是SpringCloud微服务系统中的一个组件,实现了链路追踪解决方案.可以定位一个请 ...

  2. Ant Design Pro 改变默认启动端口号

    找到package.json文件,找到图位置加--port即可.

  3. 备用APC队列

     Windows内核分析索引目录:https://www.cnblogs.com/onetrainee/p/11675224.html 备用APC队列 占坑:这一节跟进程挂靠相关联,我们先把进程挂靠给 ...

  4. python 对字典分别按照key值、value值进行排序

    1.sorted函数首先介绍sorted函数,sorted(iterable,key,reverse),sorted一共有iterable,key,reverse这三个参数. 其中iterable表示 ...

  5. JavaScript 字符串是否包含某个字符串

    字符串方式 indexOf()   (推荐) var str = "123"; console.log(str.indexOf("3") != -1 ); // ...

  6. Python Web(一)

    Infi-chu: http://www.cnblogs.com/Infi-chu/ 一.Web框架 1.socket网络编程 架构:C/S 协议:TCP/UDP 传输层 2.Web应用 架构:B/S ...

  7. [转]Outlook 2016 will not display Web linked images

    本文转自:https://community.spiceworks.com/topic/1952626-outlook-2016-will-not-display-web-linked-images ...

  8. OPENGL 入门

    检测设备支持版本,判断是否支持opengl 2.0版本 初始化设置OpenGLES2.0 实现接口GLSurfaceView.Renderer 渲染 绘制图形 1.检测设备支持版本,判断是否支持ope ...

  9. hadoop节点动态删除与增加

    动态删除 1)修改配置文件 修改hdfs-site.xml文件,适当减小dfs.replication的数量,增加dfs.hosts.exclude选项 vi hdfs-site.xml <pr ...

  10. CentOS安装docker-compose

    一.compose简介 compose是一个定义和运行多容器的docker应用的工具.compose 通过yaml文件配置应用服务,然后仅需一个命令就可以创建和运行所有配置中的服务. 二.compos ...