Django_練習(xí)二

一、知識(shí)點(diǎn)url終止符/單表數(shù)據(jù)的三種方式

  • url后加終止符防止正則匹配的唯一性
from django.conf.urls import url
from django.contrib import admin
from cm import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    #防止截胡
    url(r'^business$',views.business),
]
  • 獲取單表數(shù)據(jù)的三種方式
    all / values / values_list

all相當(dāng)于select * from 表 返回的Queryset類(lèi)型,Queryset中包含的是表每一行返回的對(duì)象

# Queryset[obj(字段),obj,obj]
obj = models.表.objects.all()
#調(diào)用方法是循環(huán)出每個(gè)對(duì)象,調(diào)用他們的字段(屬性)

values相當(dāng)于select 字段 from 表 返回的Queryset類(lèi)型,Queryset中包含的是每一行數(shù)據(jù)字典的形式返回k代值字段,v代值數(shù)據(jù)

# Queryset[{caption:'測(cè)試'},{},{}]
#select caption from business
v = models.Business.objects.values('caption')
#調(diào)用循環(huán)出字典,使用字典.k 顯示v

values_list相當(dāng)于select 字段 from 表 返回的Queryset類(lèi)型,Queryset中包含的是每一行數(shù)據(jù)元組的形式返回字段數(shù)據(jù)

# Queryset[(1,運(yùn)維部),(),()]
vv = models.Business.objects.values_list('caption')
#調(diào)用的時(shí)候通過(guò)元組取值用腳標(biāo)的方法
  • 獲取跨表數(shù)據(jù)非對(duì)象取值
    兩個(gè)表關(guān)聯(lián)時(shí),不用對(duì)象取值單一的取另一個(gè)表的字段時(shí)用__字段(雙下滑線加字段)
host 關(guān)聯(lián)business
#b__coption直接調(diào)用b對(duì)象的coption字段queryset[{'b__coption:值}]
#對(duì)應(yīng)在html調(diào)用時(shí).b__coptin
v = models.Host.objects.values('b__coption')

#被關(guān)聯(lián)對(duì)象通過(guò)關(guān)聯(lián)對(duì)象類(lèi)名__字段
v = models.Business.objects.filter(host__nid=1).values('caption')

二、練習(xí)

(1)、創(chuàng)建文件夾名為cm的app文件
python manage.py startapp cm

(2)、在setting.py配置
1、創(chuàng)建靜態(tài)文件,先創(chuàng)建static文件目錄,在setting.py中添加static路徑
STATICFILES_DIRS=(os.path.join(BASE_DIR,'static'),)注:結(jié)尾逗號(hào)
2、加入cm模塊為了model.py的創(chuàng)建
INSTALLED_APPS = ['cm']
3、配置mysql連接

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'cmtest',
        'USER':'root',
        'PASSWORD':'root',
        'HOST':'localhost',
        'PORT':'3306',
    }
}

(3)、 在__init__.py創(chuàng)建數(shù)據(jù)庫(kù)連接

import pymysql
pymysql.install_as_MySQLdb()

(4)、創(chuàng)建models.py
知識(shí)點(diǎn):
創(chuàng)建表時(shí)會(huì)默認(rèn)創(chuàng)建自增列id字段
創(chuàng)建兩個(gè)表的字段關(guān)系用ForeignKey
ForeignKey的變量名實(shí)際是關(guān)聯(lián)表的對(duì)象,實(shí)際字段是變量名_id

1.編寫(xiě)models.py

from django.db import models

# Create your models here.
class Business(models.Model):
    #id不寫(xiě)默認(rèn)自增
    caption = 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('Business', to_field='id')

2.python manage.py makemigrations
3.python manage.py migrate

(5)編寫(xiě)url.py
知識(shí)點(diǎn)$終止符防止截胡

from django.conf.urls import url
from django.contrib import admin
from cm import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    #url 對(duì)應(yīng)函數(shù)跳轉(zhuǎn)
    url(r'^business$',views.business),

]

(6)編寫(xiě)views

def business(request):
    if request.method == 'GET':
        # Queryset[obj(id,caption,code),obj,obj]
        obj = models.Business.objects.all()

        # Queryset[{caption:'測(cè)試'},{},{}]
        #select caption from business
        v = models.Business.objects.values('caption')

        ## Queryset[(1,運(yùn)維部),(),()]
        vv = models.Business.objects.values_list('caption')
        return render(request,'business.html',{'obj':obj,'obj1':v,'obj2':vv})

(7)編寫(xiě)templates

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>業(yè)務(wù)線</h1>
    <ul>
        {% for i in obj %}
        <li>{{ i.id }}-{{ i.caption }}</li>
        {% endfor %}
    </ul>

    <h1>業(yè)務(wù)線字典</h1>
    <ul>
        {% for i in obj1 %}
        <li>{{ i.caption }}</li>
        {% endfor %}
    </ul>

      <h1>業(yè)務(wù)線元組</h1>
    <ul>
        {% for i in obj2 %}
        <li>{{ i.0 }}</li>
        {% endfor %}
    </ul>
</body>
</html>

(8)頁(yè)面效果展示


image.png

(9)頁(yè)面計(jì)數(shù)forloop

forloop.counter        從1開(kāi)始
forloop.counter0       從0開(kāi)始
forloop.recounter0     倒敘從0
forloop.recounter      倒敘
forloop.last           是否是最后
forloop.first          是否是第一個(gè) 
forloop.parentloop     嵌套循環(huán)使用

                                        頁(yè)面展示
image.png

model.py

def host(request):
    if request.method == 'GET':
        # Queryset[obj(id,caption,code),obj,obj]
        obj = models.Host.objects.all()
        b_name = models.Business.objects.all()
        return render(request,'host.html',{'obj':obj,'b': b_name})
    elif request.method =='POST':
        h = request.POST.get('hostname')
        i = request.POST.get('ip')
        p = request.POST.get('port')
        b_id = request.POST.get('b_name')

        models.Host.objects.create(
            hostname=h,
            ip= i,
            port=p,
            b_id=b_id
        )
        return  redirect('/host')

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hidden{
            display: none;
        }
        .backgroud{
            position: fixed;
            left: 0;
            right: 0;
            bottom: 0;
            top: 0;
            background:black;
            opacity:0.3;
            z-index: 100;
        }
        .add_modal{
             position: fixed;
            height: 400px;
            width: 500px;
            top: 200px;
            left: 500px;
            background:white;
            z-index: 101;
        }
    </style>
</head>
<body>
<div class="backgroud hidden">
    <div class="add_modal">
    <form action="host" method="post">
        <input type="text" name="hostname">
        <br>
        <input type="text" name='ip'>
        <br>
        <input type="text" name="port">
        <br>
        <select name="b_name">
            {% for i in b %}
            <option value="{{i.id  }}">{{ i.caption }}</option>
            {% endfor %}
        </select>
        <input type="submit">
    </form>
    </div>
</div>
    <h1>業(yè)務(wù)線</h1>
    <input type="button" class="add" value="添加" >
    <ul>
        {% for i in obj %}
        <li>{{ forloop.counter }}{{ i.hostname }}-{{ i.ip }}-{{i.port }}-{{ i.b.caption }}</li>
        {% endfor %}
    </ul>
<script src="/static/jquery-1.12.4.js"></script>
<script>
    $(function () {
        $('.add').click(function () {
            $('.backgroud').removeClass('hidden')
        })
    })
</script>
</body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容