【Django】一对多表结构
1.创建project数据库表
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01', #新增app
]
配置settings.py
from django.db import models # Create your models here. class Business(models.Model):
# id 系统默认id列,自增,主键
caption = models.CharField(max_length=32) # 32表示字符长度 class Host(models.Model):
nid = models.AutoField(primary_key=True)
hostname = models.CharField(max_length=64,db_index=True)
ip = models.GenericIPAddressField(protocol='ipv4',db_index=True)
port = models.IntegerField()
b = models.ForeignKey(to='Business',to_field='id')
app01/models.py 创建两个简单的数据库表,通过ForeignKey外键关联
运行:
python manage.py makemigrations
python manage.py migrate
Ok后,使用Navicat Premium软件方可查看!
2.操作数据库表

运行Navicat
点击连接,使用SQLite抓取数据

点击确认

获取单表单数据的三种方式
from django.contrib import admin
from django.conf.urls import url
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^business/', views.business),
]
project/urls
from django.shortcuts import render,HttpResponse,redirect
from app01 import models
# Create your views here. def business(requset):
v1 = models.Business.objects.all()
#QuerySet
#[obj(id,caption,code),obj(id,caption,code),obj(id,caption,code)] v2 = models.Business.objects.all().values('id','caption')
# QuerySet
# [{'id':1,'caption':'苹果'},{'id':2,'caption':''香蕉},{'id':3,'caption':'菠萝'},{'id':4,'caption':'梨子'}] v3 = models.Business.objects.all().values_list('id','caption')
# QuerySet
# [(0,苹果),(2,香蕉)]
return render(requset,'business.html',{'v1':v1,'v2':v2,'v3':v3})
app01/views.py
from django.db import models # Create your models here. class Business(models.Model):
# id
caption = models.CharField(max_length=32)
code = models.CharField(max_length=32,null=True,default='apple')
app01/models.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>业务线列表(列表)</h1>
<ul>
{% for row in v1 %}
<li>{{ row.id }}-{{ row.caption }}-{{ row.code }}</li>
{% endfor %}
</ul>
<h1>业务线列表(字典)</h1>
<ul>
{% for row in v2 %}
<li>{{ row.id }}-{{ row.caption }}</li>
{% endfor %}
</ul>
<h1>业务线列表(元组)</h1>
<ul>
{% for row in v3 %}
<li>{{ row.0 }}-{{ row.1 }}</li>
{% endfor %}
</ul>
</body>
</html>
templates/business.html
效果图

一对多跨表操作(第一种)
from django.contrib import admin
from django.conf.urls import url
from app01 import views
# from django.urls import path urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^business/', views.business),
url(r'^host/', views.host), #在business基础上
]
project/urls.py
from django.db import models # Create your models here. class Business(models.Model):
# id
caption = models.CharField(max_length=32)
code = models.CharField(max_length=32,null=True,default='apple') class Host(models.Model):
nid = models.AutoField(primary_key=True)
hostname = models.CharField(max_length=64,db_index=True)
ip = models.GenericIPAddressField(protocol='ipv4',db_index=True)
port = models.IntegerField()
b = models.ForeignKey(to='Business',to_field='id')
app01/models.py
from django.shortcuts import render,HttpResponse,redirect
from app01 import models
# Create your views here. def host(request):
v1 = models.Host.objects.filter(nid__gt=0)
#for row in v1:
#print(row.nid,row.hostname,row.ip,row.port,row.b_id,row.b.id,row.b.caption,row.b.code,sep='\t') # return HttpResponse('戴利祥')
return render(request,'host.html',{'v1': v1})
app01/views.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>业务线列表(列表)</h1>
<table border="">
<thead>
<tr>
<th>主机名字</th>
<th>IP</th>
<th>端口</th>
<th>业务线名称</th>
<th>业务线编码</th>
</tr>
</thead>
<tbody>
{% for row in v1 %}
<tr aa="{{ row.nid }}" ab="{{ row.b.id }}">
<td>{{ row.hostname }}</td>
<td>{{ row.ip }}</td>
<td>{{ row.port }}</td>
<td>{{ row.b.caption }}</td>
<td>{{ row.b.code }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
templates/host.html
效果图:

一对多跨表操作(第二种,第三种):
def host(request):
v1 = models.Host.objects.filter(nid__gt=0)
for row in v1:
print(row.nid,row.hostname,row.ip,row.port,row.b_id,row.b.id,row.b.caption,row.b.code,sep='\t') v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption') #获取到的值为字典
# print(v2)
for row in v2:
print(row['nid'],row['hostname'],row['b_id'],row['b__caption']) v3 = models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption') #获取到的值为元组
# #print(v3)
for row in v3:
print(row) # return HttpResponse('你好')
return render(request,'host.html',{'v1': v1, 'v2':v2 ,'v3':v3})
app01/views.py
print输出结果:

刷新:http://127.0.0.1:8000/host/

模拟对话框增加一对多数据示例
from django.shortcuts import render,HttpResponse,redirect
from app01 import models
# Create your views here. def business(requset):
v1 = models.Business.objects.all()
#QuerySet
#[obj(id,caption,code),obj(id,caption,code),obj(id,caption,code)] v2 = models.Business.objects.all().values('id','caption')
# QuerySet
# [{'id':1,'caption':'苹果'},{'id':2,'caption':''香蕉},{'id':3,'caption':'菠萝'},{'id':4,'caption':'梨子'}] v3 = models.Business.objects.all().values_list('id','caption')
# QuerySet
# [(0,苹果),(2,香蕉)]
return render(requset,'business.html',{'v1':v1,'v2':v2,'v3':v3}) def host(request):
if request.method == 'GET':
v1 = models.Host.objects.filter(nid__gt=0)
v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
v3 = models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption') b_list= models.Business.objects.all() return render(request,'host.html',{'v1': v1, 'v2':v2 , 'v3':v3 ,'b_list':b_list}) elif request.method == 'POST':
h = request.POST.get('hostname')
i = request.POST.get('ip')
p = request.POST.get('port')
b = request.POST.get('b_id')
# models.Host.objects.create(hostname=h,
# ip=i,
# port=p,
# b=models.Business.objects.get(id=b)
# )
models.Host.objects.create(hostname=h,
ip=i,
port=p,
b_id=b,
)
return redirect('/host') #以get分方式重新访问http://127.0.0.1:8000/host/
app01/views.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.hide{
display: none;
}
.shade{
position: fixed;
top: 0;
right:0 ;
left: 0;
bottom: 0;
background: black;
opacity: 0.6;
z-index: 100;
}
.add-modal{
position: fixed;
height: 300px;
width: 400px;
top: 100px;
left: 50%;
z-index: 101;
border: 1px solid red;
background: white;
margin-left: -200px;
}
</style>
</head>
<body>
<h1>主机列表(列表)</h1>
<div>
<input id="add_host" type="button" value="添加"/> <!--模态对话框-->
</div>
<table border=""> <thead>
<tr>
<th>主机序号</th>
<th>主机名字</th>
<th>IP</th>
<th>端口</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v1 %}
<tr aa="{{ row.nid }}" ab="{{ row.b.id }}" ac="{{ row.b.code }}">
<td>{{ forloop.counter }}</td>
<td>{{ row.hostname }}</td>
<td>{{ row.ip }}</td>
<td>{{ row.port }}</td>
<td>{{ row.b.caption }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<h1>主机列表(字典)</h1>
<table border="">
<thead>
<tr>
<th>主机名字</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v2 %}
<tr aa="{{ row.nid }}" ab="{{ row.b__id }}">
<td>{{ row.hostname }}</td>
<td>{{ row.b__caption }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</table>
<h1>主机列表(元组)</h1>
<table border="">
<thead>
<tr>
<th>主机名字</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v3 %}
<tr aa="{{ row.0 }}" ab="{{ row.2}}">
<td>{{ row.1 }}</td>
<td>{{ row.3 }}</td>
</tr>
{% endfor %}
</tbody>
</table> <div class="shade hide"></div> <!--遮罩层,全屏-->
<div class="add-modal hide"> <!--弹出框-->
<form method="POST" action="/host/"> <!--编辑弹出框内容-->
<div class="group">
<input type="text" placeholder="主机名" name="hostname"/>
</div> <div class="group">
<input type="text" placeholder="IP" name="ip"/>
</div> <div class="group">
<input type="text" placeholder="端口" name="port"/>
</div> <div class="group">
<select name="b_id">
{% for op in b_list %}
<option value="{{ op.id }}">{{ op.caption }}</option>
{% endfor %}
</select>
</div> <input type="submit" value="提交"/>
<input id="cancel" type="button" value="取消"/>
</form>
</div> <script src="/static/jquery-1.12.4.js"></script> <!--JS文件-->
<script>
$(function () { <!--页面框架加载完成--> $('#add_host').click(function () { <!--绑定事件-->
$('.shade,.add-modal').removeClass('hide'); <!--点击添加按钮,呼出遮罩层与弹出框-->
}); $('#cancel').click(function () {
$('.shade,.add-modal').addClass('hide');
}); })
</script>
</body>
</html>
templates/host.html
新增static/jquery-1.12.4.js 文件
https://files.cnblogs.com/files/dalyday/jquery-1.12.4.js

【Django】一对多表结构的更多相关文章
- django migrate生成表结构DateTimeField 类型加了6位精度别的框架无法调用的问题?
背景介绍 django migrate 生成表结构时,对于DateTimeField 类型的处理是加了6位精度的,只用django处理是没有任何问题的,但是如何别的框架来读取这种字段会读取不到该字段值 ...
- python 全栈开发,Day98(路飞学城背景,django ContentType组件,表结构讲解)
昨日内容回顾 1. 为什么要做前后端分离? - 前后端交给不同的人来编写,职责划分明确. - API (IOS,安卓,PC,微信小程序...) - vue.js等框架编写前端时,会比之前写jQuery ...
- mysql一对多表结构,查询一的信息的同时统计多的数量
res_resource_catalog表对于res_info_item表是一对多, 查询res_resource_catalog信息的同时,统计res_info_item中该条res_resourc ...
- Python - Django - ORM 一对一表结构
当一张表的某一些字段查询的比较频繁,另外一些字段查询的不是特别频繁,可以把不怎么常用的字段 单独拿出来做成一张表,然后用一对一的表关联起来 这样既保证数据都完整的保存下来,又能保证检索更快 model ...
- djangoORM 修改表结构/字段/外键操作
Django支持修改表结构 把max_length=64 改为60 再执行一遍 python manage.py makemigrations python manage.py migrate 如果是 ...
- Django中的Model(表结构)
Model(表设计) 在这里只提经常用到的三种联表结构: 一对多:models.ForeignKey(其他表) 多对多:models.ManyToManyField(其他表) 一对一:models.O ...
- django 表结构
django 表结构 一:查看orm写的sq语句:如果对某个语句不清楚的话可以调用queryset的的query方法来查看sql. 1 obj=Hostinfo.objects.filter(id=v ...
- Django模型系统——ORM表结构对应关系
对于数据库来说一般表结构只会有三种对应关系,分别是一对一.一对多和多对一,下面分别介绍: 1.一对多 何为一对多,例如一个学生只可能有一个班级,一个班级却又多个学生,班级表和学生表就是一对多的关系. ...
- Django models文件模型变更注意事项(表结构的修改)
表结构的修改 1.表结构修改后,原来表中已存在的数据,就会出现结构混乱,makemigrations更新表的时候就会出错 比如第一次建模型,漏了一个字段,后来补上了.(经常遇到模型字段修改) 重新ma ...
随机推荐
- egret之纹理填充模式(上下填充)
首先,我们准备两张图片,一张作为背景“瓶子”,一张作位填充物“饮料”. 在皮肤里我们设置右边图片的填充模式为“repeat”,修改Y的缩放为:-1.,调整图片位置使之与地图重合,如下: 现在,我们可以 ...
- 基于 Javassist 和 Javaagent 实现动态切面
一.背景介绍 1.需求说明 需求是在程序运行期间,向某个类的某个方法前.后加入某段业务代码,或者直接替换整个方法的业务逻辑,即业务方法客制化.注意是运行期间动态更改,做到无侵入,而不是事先在代码中写死 ...
- Spring系列(五):Spring AOP源码解析
一.@EnableAspectJAutoProxy注解 在主配置类中添加@EnableAspectJAutoProxy注解,开启aop支持,那么@EnableAspectJAutoProxy到底做了什 ...
- NOIP 2009 最优贸易 题解
一道最短路的题,找一个买入和卖出相差最高的点即可,我们先以1为起点跑spfa,d1[x]不再表示距离而表示能够经过权值最小的节点的权值即 if(d1[y]>min(d1[x],price[y]) ...
- 关于Ubunto在VMwark中无法全屏。
1.右键点击Ubunto桌面,进入终端 输入: 1.sudo apt-get install open-vm* 安装依赖项 2.sudo apt-get install open-vm-tools ...
- 一起来读Netty In Action之传输(三)
当我们的应用程序需要接受比预期多很多的并发连接的时候,我们需要从阻塞传输切换到非阻塞传输上去,如果是我们的网络编程是基于jdk提供的API进行开发地的话,这种传输模式的切换几乎要我们重构整个网络传输相 ...
- JSON和Map,List,String互相转换
1)Map 和 JSON 互相转换 Map 转成 JSON Map<String, List> map = new HashMap<>(); map.put("xAx ...
- mysql5.7指定字符集
在这个配置下面加上下面这行就可以 [mysqld] character_set_server=utf8 重启后: mysql> show variables like 'char%';+---- ...
- redis持久化的两种方式RDB和AOF
原文链接:http://www.cnblogs.com/tdws/p/5754706.html Redis的持久化过程中并不需要我们开发人员过多的参与,我们要做的是什么呢?除了深入了解RDB和AOF的 ...
- 零基础一年拿下BAT三家offer
背景 1.本人本科一本双非垫底的那种,硕士211.本硕电子通信,完全0基础,转行一年. 2.研一上第一学期上课+外派到老师合作公司写MATLAB.去年4月开始学习Java. 起步 1.实话说,刚决定转 ...