1. 程式人生 > >Django框架學習筆記(15.增加一對多資料簡易示例)

Django框架學習筆記(15.增加一對多資料簡易示例)

在上一篇建立好的Django工程的基礎上:

urls.py:

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
url(r'^business$', views.business),
url(r'^host$', views.host),
]

views.py:

from django.shortcuts import 
render,redirect from django.shortcuts import HttpResponse from app01 import models # Create your views here. def business(request): v1 = models.Business.objects.all() v2 = models.Business.objects.all().values('id', 'caption') v3 = models.Business.objects.all().values_list('id', 'caption') return
render(request, '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_id=b) return redirect('/host')

models.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)



class Host(models.Model):
    nid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32, db_index=True)
    ip = models.GenericIPAddressField(db_index=True)
    port = models.IntegerField()
    b = models.ForeignKey(to="Business", to_field='id', on_delete=models.CASCADE)

host.html(用到一個JS檔案,這裡就不寫出來了):

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
.hide {
            display: none;
}

        .shade {
            position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: black;
opacity: 0.6;
z-index: 100;
}

        .add-model {
            position: fixed;
height: 300px;
width: 400px;
top: 100px;
left: 50%;
z-index: 101;
border: 1px solid red;
background-color: 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 hid="{{ row.nid }}" bid="{{ row.b_id }}">
            <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 hid="{{ row.nid }}" bid="{{ row.b_id }}">
            <td>{{ row.hostname }}</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 v3 %}
        <tr hid="{{ row.0 }}" bid="{{ row.2 }}">
            <td>{{ row.1 }}</td>
            <td>{{ row.3 }}</td>
        </tr>
{% endfor %}
    </tbody>
</table>
<div class="shade hide"></div>
<div class="add-model 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>
            <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/jquery1.js"></script>
<script>
$(function () {
        $('#add_host').click(function () {
            $('.shade,.add-model').removeClass('hide')
        });
$('#cancel').click(function () {
            $('.shade,.add-model').addClass('hide')
        });
})
</script>
</body>
</html>

執行: