Django 外键、多对多插入数据方法
models.py
class UserInfo(models.Model):
username = models.CharField(max_length=64,db_column='username')
passwd = models.CharField(max_length=64,db_column='password')
register_date = models.DateTimeField(max_length=32,db_column='register_date')
last_login_date = models.DateTimeField(max_length=32,db_column='last_login_date',null=True) class Meta:
app_label = 'simple'
db_table = 'user_info' class ServerInfo(models.Model):
hostname = models.CharField(max_length=32,db_column='hostname')
port = models.IntegerField(max_length=32,db_column='port')
status = models.CharField(max_length=32,db_column='status') class Meta:
app_label = 'simple'
db_table = 'server_info' class Publisher(models.Model):
name = models.CharField(max_length=32)
address = models.CharField(max_length=32)
state = models.CharField(max_length=32)
nation = models.CharField(max_length=32)
website = models.URLField(max_length=32) class Author(models.Model):
first_name = models.CharField(max_length=32)
last_name = models.CharField(max_length=32)
email = models.EmailField() class Book(models.Model):
title = models.CharField(max_length=32,unique=True)
author = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
pubDate = models.CharField(max_length=32)
views.py
def addBook(request):
if request.method == 'POST':
print("进入addbook post")
print(request.POST)
name = request.POST['name']
author = request.POST.getlist('author')# 当获取多个数值的时候,使用getlist
publisher = request.POST['publisher']
p1 = Publisher.objects.get(id=publisher)#先在publisher表中查询出前端选中出版社对应的对象
date = request.POST['publisherDate']
b1 = Book(title=name,publisher=p1,pubDate=date)
b1.save()#普通插入的数据和外键插入的数据需要先save()
b1 = Book.objects.get(title=name)#查出书名对象,也就是获取要插入的多对多数据项
if len(author) == 1:
b1.author.add(author[0])#多对多使用add方法进行插入
b1.save()
return redirect("/displayBook/")
elif len(author) == 0:#当用户没有选中作者
return render(request,'addBook.html',{"status":"添加出版社失败,没有选择作者"})
else:#循环插入用户选中的多个作者
for person in author:
b1.author.add(person)#多对多使用add方法进行插入
b1.save()
return redirect("/displayBook/")
print("进入addbook get") #用户从库中获取页面可选的内容,get请求
bookList = Book.objects.all()
publisherList = Publisher.objects.all()
authorList = Author.objects.all()
print(bookList,publisherList,authorList)
return render(request, 'addBook.html',{'books':bookList,
'publishers':publisherList,
'authors':authorList})
前端页面:
{% block head-menu %}
<table border=1 style="margin-left:13%;margin-top: 3%;height: 30px;width: 1000px">
<tr >
<td>书名</td>
<td>作者</td>
<td>出版社</td>
<td>出版日期</td>
</tr>
{% for book in books %}
{% if forloop.counter|divisibleby:"2" %}
<tr style="background-color: skyblue;">
<td>{{ book.title }}</td>
<td>{% for authorObj in book.author.select_related %} {{ authorObj.first_name }} {{ authorObj.last_name }} {% endfor %}</td>
<td>{{ book.publisher.name }}</td>
<td>{{ book.pubDate }}</td>
</tr>
</tr>
</tr>
{% else %}
<tr style="background-color: salmon;">
<td>{{ book.title }}</td>
<td>{% for authorObj in book.author.select_related %} {{ authorObj.first_name }} {{ authorObj.last_name }} {% endfor %}</td>
<td>{{ book.publisher.name }}</td>
<td>{{ book.pubDate }}</td>
</tr>
{% endif %}
{% endfor %}
</table>
<a href="/backend/"><button type="button" class="btn btn-primary btn-sm" style="margin-left: 43%;margin-top: 10%">返回</button></a>
{% endblock %}
Django 外键、多对多插入数据方法的更多相关文章
- django model 插入数据方法
需要插入的数据表结构如下: class UserInfo(models.Model): user_id =models.AutoField(primary_key=True) user_name=mo ...
- day42——外键的限制和解决方法、外键的三种约束模式、修改表(单表查询)
day42 外键的限制和解决方法 可以添加外键关联的那个字段可以是 被唯一(unique)约束的字段 或者 主键 限制:+ 由于外键的使用,致使多个表之间产生了联系,当我们对这些表进行更新或删除操作的 ...
- SQLServer 自增主键创建, 指定自增主键列值插入数据,插入主键
http://blog.csdn.net/zh2qiang/article/details/5323981 SQLServer 中含自增主键的表,通常不能直接指定ID值插入,可以采用以下方法插入. 1 ...
- Homework 1_SQL Server中由于外键约束而删除数据失败
SQL Server中由于外键约束而删除数据失败 原因分析:外键约束问题.在配置文件中配置了一对一的关系,外键也是唯一的.数据库中数据有严格的依赖关系. 而在业务逻辑中,在往数据库里删除数据之前,却忘 ...
- C# 批量插入数据方法
批量插入数据方法 void InsertTwo(List<CourseArrangeInfo> dtF) { Stopwatch watch = new Stopwatch(); watc ...
- sql实现同时向主表和子表插入数据方法
使用sql语句实现同时向主表和子表插入数据方法: Oracle: -- oracle创建sequence create sequence SEQ_test minvalue 1 maxvalue 99 ...
- 072 01 Android 零基础入门 01 Java基础语法 09 综合案例-数组移位 04 综合案例-数组移位-在指定位置处插入数据方法
072 01 Android 零基础入门 01 Java基础语法 09 综合案例-数组移位 04 综合案例-数组移位-在指定位置处插入数据方法 本文知识点:综合案例-数组移位-在指定位置处插入数据方法 ...
- Django QuerySet 方法梳理 。model外键 多对多的保存
引用:https://feifeiyum.github.io/2017/03/28/python-django-queryset/ 说明 Models 层是 Django 框架中最强大的部分之一, 大 ...
- django中两张表有外键关系的相互查找方法,自定义json编码方法
两张通过外键联系的表,如何在一张表上根据另一张表上的属性查找满足条件的对象集? 平常查找表中数据的条件是python中已有的数据类型,通过名字可以直接查找.如果条件是表中外键列所对应表的某一列,该如何 ...
随机推荐
- Bootstrap, 模态框实现值传递,自动勾选
目录 Bootstrap,模态框自动勾选,值传递 1.父页面 2. 子页面(modal) 模态框 Bootstrap,模态框自动勾选,值传递 场景: 有一个这样的需求, 在父页面有一个table, ...
- List的add方法与addAll方法的区别、StringBuffer的delete方法与deleteCharAt的区别
List的add方法与addAll方法 区别 add add是将传入的参数作为当前List中的一个Item存储,即使你传入一个List也只会另当前的List增加1个元素 addAll addAll是传 ...
- Eureka启动报错:Failed to load property source from location 'classpath:/application.yml'
原因: 将application.yml添加到classpath时, 由于变更了application.yml的编码格式(或许也改变了些代码内容), 而target内的yml文件没有实时更新, 从而导 ...
- Hyperledger Fabric 常用命令
Peer常用命令: #peer chaincode --help #peer channel list --help --logging-level <string> #<strin ...
- ffmpeg学习笔记-初识ffmpeg
ffmpeg用来对音视频进行处理,那么在使用ffmpeg前就需要ffmpeg有一个大概的了解,这里使用雷神的ppt素材进行整理,以便于复习 音视频基础知识 视频播放器的原理 播放视频的流程大致如下: ...
- gx_dlms 的杂乱记录
DLMS_ERROR_CODE_FALSE W3Jehpnc543MuwUz6ZWDshy5kwbbE9Cw CGXDLMSClient::GetData(CGXByteBuffer& rep ...
- ssh出现公钥错误问题的解决方法
问题:主机app1推送公钥时,公钥判定错误 原因:之前推过公钥,用的是ip而不是主机名(即hosts文件中的对应关系不对),导致app1的~/.ssh/known_hosts中的公钥对不上. ...
- linux命令(ubuntu18)记录...
1.解压.zip文件unzip unzip studentCRUD-master.zip 2.读写权限chmod指令 r表是读 (Read) .w表示写 (Write) .x ...
- SSM+pagehelper分页
1.maven依赖 <dependency> <groupId>com.github.jsqlparser</groupId> <artifactId> ...
- AC自动机fail树上dfs序建线段树+动态memset清空
题意:http://acm.hdu.edu.cn/showproblem.php?pid=4117 思路:https://blog.csdn.net/u013306830/article/detail ...