【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 Premium

点击连接,使用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="1">
        <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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>业务线列表(列表)</h1>
    <table border="1">
        <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>
    <h1>业务线列表(字典)</h1>
    <table border="1">
        <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="1">
        <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>

templates/host.html

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="1">

        <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="1">
        <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="1">
        <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

原文地址:https://www.cnblogs.com/dalyday/p/8891238.html

时间: 2024-10-29 01:09:07

【Django】一对多表结构的相关文章

创建一对多表结构实例 /操作的三种方式

例 1.注册App01  完成各项配置 2. 写完后自动生成一个id自增列(主键) 如果不想生成 自己写 创建两张表 3.执行创建语句 (其中还进行了一个小修改) 4.按照之前的方法 打开数据库 并输入数据 5.修改表结构 法一: 在更新时 遇到选择 因为已经存入数据 新建列默认不能为Null 默认为sa 注意输入的是字符串 刷新 法二: 法三: ====================== 接下来进行view 应该先看到业务线  再看到主机 1.urls 注意:如果同时有 bussiness

十二 .Django 一对多表ForeighKey(ORM)

一 . 一对多表ForeighKey(ORM) 1.创建ORM表 https://www.cnblogs.com/dangrui0725/p/9615641.html 一对多:子表从母表中选出一条数据一一对应,但母表的这条数据还可以被其他子表数据选择 共同点是在admin中添加数据的话,都会出现一个select选框,但只能单选,因为不论一对一还是一对多,自己都是“一” class Colors(models.Model): colors=models.CharField(max_length=1

Django -- 一对多建表增删改查

一对多表结构 ForeignKey -- 设置外键与另一张表关联 class Book(models.Model): title = models.CharField(max_length=32) pub = models.ForeignKey('Publisher', on_delete=models.CASCADE) # 外键 -- 关联表另一张表 查询 all_books = models.Book.objects.all() # 获取所有的数据 print(all_books) for

Django models文件模型变更注意事项(表结构的修改)

表结构的修改 1.表结构修改后,原来表中已存在的数据,就会出现结构混乱,makemigrations更新表的时候就会出错 比如第一次建模型,漏了一个字段,后来补上了.(经常遇到模型字段修改) 重新makemigrations,然后报错 数据库规则:除了新建表,如果你再次增加字段,数据库会有一些自动检测的东西(比如有没有默认值,是否允许为空)如果表中已经有数据,这个字段还是非空的,且没有设定默认值,后台检测不通过就会报错. 解决方法(有两种):1.新增加的字段,设置允许为空.生成表的时候,之前数据

Djaogo-Model操作数据库(增删改查、连表结构)

一.数据库操作 1.创建model表 基本结构 1 2 3 4 5 6 from django.db import models    class userinfo(models.Model):     #如果没有models.AutoField,默认会创建一个id的自增列     name = models.CharField(max_length=30)     email = models.EmailField()     memo = models.TextField() 更多字段: 1

Django-Model操作数据库(增删改查、连表结构)

一.数据库操作 1.创建model表 基本结构 1 from django.db import models 2 3 class userinfo(models.Model): 4 #如果没有models.AutoField,默认会创建一个id的自增列 5 name = models.CharField(max_length=30) 6 email = models.EmailField() 7 memo = models.TextField() 更多字段: 1.models.AutoField

Django开发之路 二(django的models表查询)

django的models表查询 一.单表查询 (1) all(): 查询所有结果 # 返回的QuerySet类型 (2) filter(**kwargs): 它包含了与所给筛选条件相匹配的对象 #返回的QuerySet类型 (3) get(**kwargs): 返回与所给筛选条件相匹配的对象,返回结果有且只有一个, #返回的models对象 如果符合筛选条件的对象超过一个或者没有都会抛出错误. (4) exclude(**kwargs): 它包含了与所给筛选条件不匹配的对象 #返回的Query

读数据库所有表和表结构的sql语句

SQL获取所有数据库名.表名.储存过程以及参数列表 1.获取所有用户名:SELECT name FROM Sysusers where status='2' and islogin='1'islogin='1'表示帐户islogin='0'表示角色status='2'表示用户帐户status='0'表示糸统帐户2.获取所有数据库名:SELECT Name FROM Master..SysDatabases ORDER BY Name3.获取所有表名SELECT Name FROM Databas

django一对多 增 删 改 查

实现一对多表查询功能 项目代码: models.py from django.db import models # Create your models here. class Classes(models.Model): """ 班级表,男 """ titile = models.CharField(max_length=32) m = models.ManyToManyField("Teachers") class Tea