day20 Django Models 操做,多表,多對多

1 Django models 獲取數據的三種方式:html

實踐:
viwes
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})

models 前端

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="SA")
class Host(models.Model):
    nid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
    port = models.IntegerField()
    b = models.ForeignKey(to="Business", to_field='id')

urlspython

from django.conf.urls import url
from django.contrib import admin
from user_manage import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^helloworld/$', views.helloword),
    url(r'^bussiness/$', views.business),
]

htmljquery

<!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>
執行生成表結構:
manage.py makemigrations
manage.py migrate

db 手動添加ajax

 

效果:數據庫

 

 

隱藏一些不須要用戶看到的的iddjango

 

 

連表操做:json

實踐:
views:
def host(request):
    v1 = models.Host.objects.all()
    for row in v1:
        print(row.nid,row.hostname,row.ip,row.port,row.b_id,row.b.caption,row.b.code,row.b.id,sep='\t')
    return render(request,'host.html',{'v1':v1})

models:服務器

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="SA")
class Host(models.Model):
    nid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
    port = models.IntegerField()
    b = models.ForeignKey(to="Business", to_field='id')

urls: ide

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

html:

<!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>
            </tr>
        </thead>
        <tbody>
            {% for row in v1 %}
            <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
                <td>{{ row.hostname }}</td>
                <td>{{ row.ip }}</td>
                <td>{{ row.port }}</td>
                <td>{{ row.b.caption }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

數據庫信息:

 

效果:

 

 

 
 多個連表:

 

 從這裏想跨表都是用雙下劃線

 

 

 

字典:

 

元組:

 

實踐:

viwes:

def host(request):
    #對象
    v1 = models.Host.objects.all()
    for row in v1:
        print(row.nid,row.hostname,row.ip,row.port,row.b_id,row.b.caption,row.b.code,row.b.id,sep='\t')
    #字典
    v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
    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')
    for row in v3:
        print(row[0],row[1],row[2],row[3])
    return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3})

models:

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="SA")
class Host(models.Model):
    nid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
    port = models.IntegerField()
    b = models.ForeignKey(to="Business", to_field='id')

urls:

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

html:

<!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>
            </tr>
        </thead>
        <tbody>
            {% for row in v1 %}
            <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
                <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>
</body>
</html>

效果:

 

模板語言的計數器:

 用於顯示序號:

 

倒敘:

 

從零開始:

 

是不是最後一個:

是不是第一個:

 

顯示父循環的信息:

 

 

 

增長數據:

實踐:
views:
def host(request):
    if request.method == 'GET':
        #對象
        v1 = models.Host.objects.all()
        #字典
        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:

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="SA")
class Host(models.Model):
    nid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
    port = models.IntegerField()
    b = models.ForeignKey(to="Business", to_field='id')

urls:

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

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <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 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-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>
    <script>
        $(function(){
            $('#add_host').click(function(){
                $('.shade,.add-modal').removeClass('hide');
            });
            $('#cancel').click(function(){
                $('.shade,.add-modal').addClass('hide');
            });
        })
    </script>
</body>
</html>

效果:

 

 Ajax 提交:

 

實踐Ajax 悄悄提交:
views:
def host(request):
    if request.method == 'GET':
        #對象
        v1 = models.Host.objects.all()
        #字典
        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/')
def test_ajax(request):
    h = request.POST.get('hostname')
    i = request.POST.get('ip')
    p = request.POST.get('port')
    b = request.POST.get('b_id')
    if h and len(h) >5:
        models.Host.objects.create(hostname=h, ip=i, port=p, b_id=b)
        return HttpResponse('OK')
    else:
        return HttpResponse('主機名過短了')

urls:

from django.conf.urls import url
from django.contrib import admin
from user_manage import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^helloworld/$', views.helloword),
    url(r'^bussiness/$', views.business),
    url(r'^host/$', views.host),
    url(r'^test_ajax/$', views.test_ajax),
]

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <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 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-modal hide">
        <form method="POST" action="/host/">
            <div class="group">
                <input id="host" type="text" placeholder="主機名" name="hostname" />
            </div>
            <div class="group">
                <input id="ip" type="text" placeholder="IP" name="ip" />
            </div>
            <div class="group">
                <input id="port" type="text" placeholder="端口" name="port" />
            </div>
            <div class="group">
                <select id="sel" name="b_id">
                    {% for op in b_list %}
                    <option value="{{ op.id }}">{{ op.caption }}</option>
                    {% endfor %}
                </select>
            </div>
            <input type="submit" value="提交" />
            <a id="ajax_submit">悄悄提交</a>
            <input id="cancel" type="button" value="取消" />
        </form>
    </div>
    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        $(function(){
            $('#add_host').click(function(){
                $('.shade,.add-modal').removeClass('hide');
            });
            $('#cancel').click(function(){
                $('.shade,.add-modal').addClass('hide');
            });
        })
        $('#ajax_submit').click(function () {
            $.ajax({
                url: '/test_ajax/',
                type:'POST',
                data:{'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},
                success: function (data) {
                    if(data == 'OK'){
                        location.reload()
                    }else{
                        alert(data)
                    }
                }
            })
        })
    </script>
</body>
</html>

效果:

 

 

須要轉換爲json 
前端須要反序列化:

 

添加一個標籤,經過jquery 添加error 數據

 

 

 

 

 

 

 多對多:

 

建立多對多:
  方式一: 
            自定義關係表:

            

           

方式二:
      自動建立關鍵關係表:
      最多生成3列:

      

 

 進行間接操做:

 

 

 模板裏循環:

 

 添加錯誤處理函數,就是當服務器完全出問題的時候:

 

列表:

 

 

 

 

 

相關文章
相關標籤/搜索