python的学习第20天 django继续学习(数据库)
django
django操作数据库
写一个例子,建立数据库并取数据前端浏览器显示
先在路由系统 url.py中添加
"""day20 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^business/', views.business), ]
在视图views.py中添加
from django.shortcuts import render 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}) #依次把他们返回给浏览器
再在template模版中添加business.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1 style="color: burlywood">v1对象</h1> <ul> {% for row in v1 %} <li> {{row.id}} ++{{row.caption}} ++{{row.code}}</li> {% endfor %} </ul> <h1 style="color: aquamarine">v2字典</h1> <ul> {% for row in v2 %} <li> {{row.id}} ++{{row.caption}}</li> {% endfor %} </ul> <h1 style="color: red">v3对象元祖</h1> <ul> {% for row in v3 %} <li> {{row.0}} ++{{row.1}}</li> {% endfor %} </ul> </body> </html>
需要主要的是,需要手动在business表中添加数据才能显示

写一个主机列表查看的功能(数据这sqllite3中)
url.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^buisiness/$', views.buisiness), url(r'^host/$', views.host), ]
views.py
def host(request):
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')
return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3})
/templates/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>
效果:

序号有关系的参数,只要有for就有下面的参数
<td>{{ forloop.counter }}</td> 1。。。 <td>{{ forloop.counter0 }}</td> 0.。。。。 <td>{{ forloop.revcounter }}</td> 。。。。。1 <td>{{ forloop.revcounter0 }}</td> .。。。。。0 <td>{{ forloop.first }}</td> 是否是第一 true fale <td>{{ forloop.last }}</td> 是否是最后 true fale
再来一个用from表单的方式来写一个添加删除主机的列子

views.py
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.Buisiness.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')
host.html:
<!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_mode{ position: fixed; height: 500px; width: 800px; top: 60px; left:50%; z-index:101; border: 1px solid red; background:whitesmoke; margin-left: -400px; } </style> </head> <body> <h1>主机列表的查询(对象)</h1> <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> <input id="add_host" type="submit" value="添加" /> <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 id="" class="shade hide"></div> <div id="" class="add_mode 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="cancle" type="button" value="取消" /> </form> </div> <script src="/static/jquery-1.12.4.js"></script> <script> $(function () { $('#add_host').click(function () { $('.shade,.add_mode').removeClass('hide') }) $('#cancle').click(function () { $('.shade,.add_mode').addClass('hide') }) }) </script> </body> </html>
url.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^buisiness/$', views.buisiness), url(r'^host$', views.host), ]
多表对多表关系的建立
models.py
from django.db import models # Create your models here. class Buisiness(models.Model): caption = models.CharField(max_length=32) code = models.CharField(max_length=32,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='both',db_index=True) port = models.IntegerField() b = models.ForeignKey(to="Buisiness",to_field='id') class Application(models.Model): name = models.CharField(max_length=32) r = models.ManyToManyField("Host") #用到了manytomanyfield参数 这是自己管理的下面的用两个foreiginkey也是可以的自己的可以继续加表自动管理不行 #那怎么管理呢,就用r这对象实际上r代只了Host表的对象 # class HostToApp(models.Model): # hobj = models.ForeignKey(to='Host',to_field='nid') # aobj = models.ForeignKey(to='Application',to_field='id')
views.py
def app(request): if request.method == "GET": app_list = models.Application.objects.all() # for row in app_list: # print(row.name,row.r.all()) host_list = models.Host.objects.all() return render(request,'app.html',{"app_list": app_list,'host_list': host_list}) elif request.method == "POST": app_name = request.POST.get('app_name') host_list = request.POST.getlist('host_list') print(app_name,host_list) obj = models.Application.objects.create(name=app_name) obj.r.add(*host_list) return redirect('/app') def ajax_add_app(request): ret = {'status':True, 'error':None, 'data': None} app_name = request.POST.get('app_name') host_list = request.POST.getlist('host_list') obj = models.Application.objects.create(name=app_name) obj.r.add(*host_list) return HttpResponse(json.dumps(ret))
url.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^buisiness/$', views.buisiness), url(r'^host$', views.host), url(r'^test_ajax$', views.test_ajax), url(r'^app$', views.app), url(r'^ajax_add_app$', views.ajax_add_app), ]
app.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .host-tag{ display: inline-block; padding: 3px; border: 1px solid red; background-color: palevioletred; } .hide{ display: none; } .shade{ position: fixed; top: 0; right: 0; left: 0; bottom: 0; background: black; opacity: 0.6; z-index: 100; } .add-modal,.edit-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_app" type="button" value="添加" /> </div> <table border="1"> <thead> <tr> <td>应用名称</td> <td>应用主机列表</td> </tr> </thead> <tbody> {% for app in app_list %} <tr aid="{{ app.id }}"> <td>{{ app.name }}</td> <td> {% for host in app.r.all %} <span class="host-tag" hid="{{ host.nid }}"> {{ host.hostname }} </span> {% endfor %} </td> <td> <a class="edit">编辑</a> </td> </tr> {% endfor %} </tbody> </table> <div class="shade hide"></div> <div class="add-modal hide"> <form id="add_form" method="POST" action="/app"> <div class="group"> <input id="app_name" type="text" placeholder="应用名称" name="app_name" /> </div> <div class="group"> <select id="host_list" name="host_list" multiple> {% for op in host_list %} <option value="{{ op.nid }}">{{ op.hostname }}</option> {% endfor %} </select> </div> <input type="submit" value="提交" /> <input id="add_submit_ajax" type="button" value="Ajax提交" /> </form> </div> <div class="edit-modal hide"> <form id="edit_form" method="POST" action="/host"> <input type="text" name="nid" style="display:none" /> <input type="text" placeholder="应用名称" name="app" /> <select name="host_list" multiple> {% for op in host_list %} <option value="{{ op.nid }}">{{ op.hostname }}</option> {% endfor %} </select> <a id="ajax_submit_edit" >确认编辑</a> </form> </div> <script src="/static/jquery-1.12.4.js"></script> <script> $(function(){ $('#add_app').click(function(){ $('.shade,.add-modal').removeClass('hide'); }); $('#cancel').click(function(){ $('.shade,.add-modal').addClass('hide'); }); $('#add_submit_ajax').click(function(){ $.ajax({ url: '/ajax_add_app', // data: {'user': 123,'host_list': [1,2,3,4]}, data: $('#add_form').serialize(), type: "POST", dataType: 'JSON', // 内部 traditional: true, success: function(obj){ console.log(obj); }, error: function () { } }) }); $('.edit').click(function(){ $('.edit-modal,.shade').removeClass('hide'); var hid_list = []; $(this).parent().prev().children().each(function(){ var hid = $(this).attr('hid'); hid_list.push(hid) }); $('#edit_form').find('select').val(hid_list); // 如果发送到后台 // /* obj = models.Application.objects.get(id=ai) obj.name = "新Name" obj.save() obj.r.set([1,2,3,4]) */ }) }) </script> </body> </html>
浙公网安备 33010602011771号