django 進階篇

 models(模型)

  • 建立數據庫,設計表結構和字段
  • 使用 MySQLdb 來鏈接數據庫,並編寫數據訪問層代碼
  • 業務邏輯層去調用數據訪問層執行數據庫操做
import MySQLdb
 
def GetList(sql):
    db = MySQLdb.connect(user='root', db='wupeiqidb', passwd='1234', host='localhost')
    cursor = db.cursor()
    cursor.execute(sql)
    data = cursor.fetchall()
    db.close()
    return data
 
def GetSingle(sql):
    db = MySQLdb.connect(user='root', db='wupeiqidb', passwd='1234', host='localhost')
    cursor = db.cursor()
    cursor.execute(sql)
    data = cursor.fetchone()
    db.close()
    return data
View Code

django爲使用一種新的方式,即:關係對象映射(Object Relational Mapping,簡稱ORM)。html

用於實現面向對象編程語言裏不一樣類型系統的數據之間的轉換,換言之,就是用面向對象的方式去操做數據庫的建立表以及增刪改查等操做。python

優勢:1 ORM使得咱們的通用數據庫交互變得簡單易行,並且徹底不用考慮該死的SQL語句。快速開發,由此而來。mysql

缺點:1 性能有所犧牲,不過如今的各類ORM框架都在嘗試各類方法,好比緩存,延遲加載登來減輕這個問題。效果                 很顯著。jquery

           2 對於個別複雜查詢,ORM仍然力不從心,爲了解決這個問題,ORM通常也支持寫raw sql。git

1、建立表ajax

一、基本結構正則表達式

注意:sql

  一、建立表的時候,若是咱們不給表加自增列,生成表的時候會默認給咱們生成一列爲ID的自增列,固然咱們也能夠自定義數據庫

  二、若是咱們給某一列設置了外鍵的時候,生成表的時候,該列的表名會自動生成auter_id(即倆個字段中間用_鏈接起來)django

  3、建立外鍵的時候 models.ForeignKey(UserType)  ForeignKey中參數表明的類必須在其上面,不然就必須寫成字符串的形式

class Userinfo(models.Model):
    nid = models.AutoField(max_length=30,primary_key=True)
    name = models.CharField(max_length=60)
    pwd = models.CharField(max_length=30)
    time = models.DateField(auto_now=True)
    
    class Meta:
        verbose_name = '用戶名'
        verbose_name_plural = verbose_name

    def __str__(self):     #至關於tornado中的__repr__  打印對象信息
        return self.name

一  定義數據模型的擴展屬性

     經過內部類Meta給數據模型類增長擴展屬性:

     class Meta:

             verbose_name='名稱'      #表名由英文轉換成中文了

             verbose_name_plural='名稱複數形式'

             ordering='排序字段'   
一、models.AutoField  自增列 = int(11)
  若是沒有的話,默認會生成一個名稱爲 id 的列,若是要顯示的自定義一個自增列,必須將給列設置爲主鍵 primary_key=True。
2、models.CharField  字符串字段
  必須 max_length 參數
三、models.BooleanField  布爾類型=tinyint(1)
  不能爲空,Blank=True
四、models.ComaSeparatedIntegerField  用逗號分割的數字=varchar
  繼承CharField,因此必須 max_lenght 參數
5、models.DateField  日期類型 date
  對於參數,auto_now = True 則每次更新都會更新這個時間;auto_now_add 則只是第一次建立添加,以後的更新再也不改變。
6、models.DateTimeField  日期類型 datetime
  同DateField的參數
七、models.Decimal  十進制小數類型 = decimal
  必須指定整數位max_digits和小數位decimal_places
八、models.EmailField  字符串類型(正則表達式郵箱) =varchar
  對字符串進行正則表達式
九、models.FloatField  浮點類型 = double
10、models.IntegerField  整形
11、models.BigIntegerField  長整形
  integer_field_ranges = {
    'SmallIntegerField': (-32768, 32767),
    'IntegerField': (-2147483648, 2147483647),
    'BigIntegerField': (-9223372036854775808, 9223372036854775807),
    'PositiveSmallIntegerField': (0, 32767),
    'PositiveIntegerField': (0, 2147483647),
  }
12、models.IPAddressField  字符串類型(ip4正則表達式)
13、models.GenericIPAddressField  字符串類型(ip4和ip6是可選的)
  參數protocol能夠是:both、ipv四、ipv6
  驗證時,會根據設置報錯
14、models.NullBooleanField  容許爲空的布爾類型
15、models.PositiveIntegerFiel  正Integer
16、models.PositiveSmallIntegerField  正smallInteger
17、models.SlugField  減號、下劃線、字母、數字
18、models.SmallIntegerField  數字
  數據庫中的字段有:tinyint、smallint、int、bigint
1九、models.TextField  字符串=longtext
20、models.TimeField  時間 HH:MM[:ss[.uuuuuu]]
21、models.URLField  字符串,地址正則表達式
22、models.BinaryField  二進制
23、models.ImageField   圖片
2四、models.FilePathField 文件
更多字段
AutoField
一個 IntegerField, 添加記錄時它會自動增加. 你一般不須要直接使用這個字段; 若是你不指定主鍵的話,系統會自動添加一個主鍵字段到你的 model.(參閱 _自動主鍵字段)
BooleanField
A true/false field. admin 用 checkbox 來表示此類字段.
CharField
字符串字段, 用於較短的字符串.

若是要保存大量文本, 使用 TextField.

admin 用一個 <input type="text"> 來表示此類字段 (單行輸入).

CharField 要求必須有一個參數 maxlength, 用於從數據庫層和Django校驗層限制該字段所容許的最大字符數.

CommaSeparatedIntegerField
用於存放逗號分隔的整數值. 相似 CharField, 必需要有 maxlength 參數.
DateField
一個日期字段. 共有下列額外的可選參數:

Argument    描述
auto_now    當對象被保存時,自動將該字段的值設置爲當前時間.一般用於表示 "last-modified" 時間戳.
auto_now_add    當對象首次被建立時,自動將該字段的值設置爲當前時間.一般用於表示對象建立時間.
admin 用一個文本框 <input type="text"> 來表示該字段數據(附帶一個 JavaScript 日曆和一個"Today"快鍵.

DateTimeField
 一個日期時間字段. 相似 DateField 支持一樣的附加選項.
admin 用兩上文本框 <input type="text"> 表示該字段順序(附帶JavaScript shortcuts). 

EmailField
一個帶有檢查 Email 合法性的 CharField,不接受 maxlength 參數.
FileField
一個文件上傳字段.

要求一個必須有的參數: upload_to, 一個用於保存上載文件的本地文件系統路徑. 這個路徑必須包含 strftime formatting, 該格式將被上載文件的 date/time 替換(so that uploaded files don't fill up the given directory).

admin 用一個``<input type="file">``部件表示該字段保存的數據(一個文件上傳部件) .

在一個 model 中使用 FileField 或 ImageField 須要如下步驟:

在你的 settings 文件中, 定義一個完整路徑給 MEDIA_ROOT 以便讓 Django在此處保存上傳文件. (出於性能考慮,這些文件並不保存到數據庫.) 定義 MEDIA_URL 做爲該目錄的公共 URL. 要確保該目錄對 WEB 服務器用戶賬號是可寫的.
在你的 model 中添加 FileField 或 ImageField, 並確保定義了 upload_to 選項,以告訴 Django 使用 MEDIA_ROOT 的哪一個子目錄保存上傳文件.
你的數據庫中要保存的只是文件的路徑(相對於 MEDIA_ROOT). 出於習慣你必定很想使用 Django 提供的 get_<fieldname>_url 函數.舉例來講,若是你的 ImageField 叫做 mug_shot, 你就能夠在模板中以 {{ object.get_mug_shot_url }} 這樣的方式獲得圖像的絕對路徑.
FilePathField
可選項目爲某個特定目錄下的文件名. 支持三個特殊的參數, 其中第一個是必須提供的.

參數    描述
path    必需參數. 一個目錄的絕對文件系統路徑. FilePathField 據此獲得可選項目. Example: "/home/images".
match    可選參數. 一個正則表達式, 做爲一個字符串, FilePathField 將使用它過濾文件名. 注意這個正則表達式只會應用到 base filename 而不是路徑全名. Example: "foo.*\.txt^", 將匹配文件 foo23.txt 卻不匹配 bar.txt 或 foo23.gif.
recursive    可選參數.要麼 True 要麼 False. 默認值是 False. 是否包括 path 下面的所有子目錄.
這三個參數能夠同時使用.

我已經告訴過你 match 僅應用於 base filename, 而不是路徑全名. 那麼,這個例子:

FilePathField(path="/home/images", match="foo.*", recursive=True)
...會匹配 /home/images/foo.gif 而不匹配 /home/images/foo/bar.gif

FloatField
一個浮點數. 必須 提供兩個 參數:

參數    描述
max_digits    總位數(不包括小數點和符號)
decimal_places    小數位數
舉例來講, 要保存最大值爲 999 (小數點後保存2位),你要這樣定義字段:

models.FloatField(..., max_digits=5, decimal_places=2)
要保存最大值一百萬(小數點後保存10位)的話,你要這樣定義:

models.FloatField(..., max_digits=19, decimal_places=10)
admin 用一個文本框(<input type="text">)表示該字段保存的數據.

ImageField
相似 FileField, 不過要校驗上傳對象是不是一個合法圖片.它有兩個可選參數:height_field 和 width_field,若是提供這兩個參數,則圖片將按提供的高度和寬度規格保存.

該字段要求 Python Imaging Library.

IntegerField
用於保存一個整數.

admin 用一個``<input type="text">``表示該字段保存的數據(一個單行編輯框)

IPAddressField
一個字符串形式的 IP 地址, (i.e. "24.124.1.30").

admin 用一個``<input type="text">``表示該字段保存的數據(一個單行編輯框)

NullBooleanField
相似 BooleanField, 不過容許 NULL 做爲其中一個選項. 推薦使用這個字段而不要用 BooleanField 加 null=True 選項.

admin 用一個選擇框 <select> (三個可選擇的值: "Unknown", "Yes""No" ) 來表示這種字段數據.

PhoneNumberField
一個帶有合法美國風格電話號碼校驗的 CharField``(格式: ``XXX-XXX-XXXX).
PositiveIntegerField
相似 IntegerField, 但取值範圍爲非負整數(這個字段應該是容許0值的....因此字段名字取得不太好,無符號整數就對了嘛).
PositiveSmallIntegerField
相似 PositiveIntegerField, 取值範圍較小(數據庫相關)
SlugField
"Slug" 是一個報紙術語. slug 是某個東西的小小標記(短籤), 只包含字母,數字,下劃線和連字符.它們一般用於URLs.

若你使用 Django 開發版本,你能夠指定 maxlength. 若 maxlength 未指定, Django 會使用默認長度: 50. 在之前的 Django 版本,沒有任何辦法改變 50 這個長度.

這暗示了 db_index=True.

它接受一個額外的參數: prepopulate_from, which is a list of fields from which to auto-populate the slug, via JavaScript, in the object's admin form:

models.SlugField(prepopulate_from=("pre_name", "name"))
prepopulate_from 不接受 DateTimeFields.

admin 用一個``<input type="text">``表示 SlugField 字段數據(一個單行編輯框) 

SmallIntegerField
相似 IntegerField, 不過只容許某個取值範圍內的整數.(依賴數據庫)
 
TextField
一個容量很大的文本字段.

admin 用一個 <textarea> (文本區域)表示該字段數據.(一個多行編輯框).

TimeField
A time. Accepts the same auto-population options as DateField 和 DateTimeField.

admin 用一個 <input type="text"> 文本框表示該字段保存的數據(附加一些JavaScript shortcuts).

URLField
用於保存 URL. 若 verify_exists 參數爲 True (默認), 給定的 URL 會預先檢查是否存在(即URL是否被有效裝入且沒有返回404響應).

admin 用一個 <input type="text"> 文本框表示該字段保存的數據(一個單行編輯框)

USStateField
一個兩字母的美國州名縮寫.

admin 用一個 <input type="text"> 文本框表示該字段保存的數據(一個單行編輯框)

XMLField
一個校驗值是否爲合法XML的 TextField,必須提供參數: schema_path, 它是一個用來校驗文本的 RelaxNG schema 的文件系統路徑.
字段詳細
一、null=True
  數據庫中字段是否能夠爲空
二、blank=True
  django的 Admin 中添加數據時是否可容許空值
三、primary_key = False
  主鍵,對AutoField設置主鍵後,就會代替原來的自增 id 列
4、auto_now 和 auto_now_add
  auto_now   自動建立---不管添加或修改,都是當前操做的時間
  auto_now_add  自動建立---永遠是建立時的時間
5、choices
GENDER_CHOICE = (
        (u'M', u'Male'),
        (u'F', u'Female'),
    )
gender = models.CharField(max_length=2,choices = GENDER_CHOICE)
6、max_length
7、default  默認值
8、verbose_name  Admin中字段的顯示名稱
九、name|db_column  數據庫中的字段名稱
十、unique=True  不容許重複
十一、db_index = True  數據庫索引
十二、editable=True  在Admin裏是否可編輯
1三、error_messages=None  錯誤提示
1四、auto_created=False  自動建立
15、help_text  在Admin中提示幫助信息
1六、validators=[]
1七、upload-to
更多參數

二、連表結構(當咱們在類中寫上這樣的字段後,就會爲咱們自動建立一張關係表)

  • 一對多:models.ForeignKey(其餘表)
  • 一對多:就是主外鍵關係;
  • 多對多:models.ManyToManyField(其餘表)
  • 多對多:多個主外鍵的關係
  • 一對一:models.OneToOneField(其餘表)
  • 一對一:實質就是在主外鍵的關係基礎上,給外鍵加了一個UNIQUE的屬性

應用場景:

    • 一對一:在某表中建立一行數據時,有一個單選的下拉框(下拉框中的內容被用過一次就消失了)。
      例如:原有含10列數據的一張表保存相關信息,通過一段時間以後,10列沒法知足需求,須要爲原來的表再添加5列數據。
    • 一對多:當一張表中建立一行數據時,有一個單選的下拉框(能夠被重複選擇)。
      例如:建立用戶信息時候,須要選擇一個用戶類型【普通用戶】【高級用戶】【超級用戶】等。
    • 多對多:在某表中建立一行數據是,有一個能夠多選的下拉框。
      例如:建立用戶信息,須要爲用戶指定多個愛好。

2、操做表

一、基本操做

    增
    
    models.Tb1.objects.create(c1='xx', c2='oo')  增長一條數據,能夠接受字典類型數據 **kwargs

    obj = models.Tb1(c1='xx', c2='oo')
    obj.save()

    查
    
    models.Tb1.objects.get(id=123)         # 獲取單條數據,不存在則報錯(不建議)
    models.Tb1.objects.all()               # 獲取所有
    models.Tb1.objects.filter(name='seven') # 獲取指定條件的數據

    刪
    
    models.Tb1.objects.filter(name='seven').delete() # 刪除指定條件的數據

    改
    models.Tb1.objects.filter(name='seven').update(gender='0')  # 將指定條件的數據更新,均支持 **kwargs
    obj = models.Tb1.objects.get(id=1)
    obj.c1 = '111'
    obj.save()                                                 # 修改單條數據
增刪改查

二、進階操做(了不得的雙下劃線)

利用雙下劃線將字段和對應的操做鏈接起來

獲取個數
    
    models.Tb1.objects.filter(name='seven').count()
    
    大於,小於
    
    models.Tb1.objects.filter(id__gt=1)              # 獲取id大於1的值
    models.Tb1.objects.filter(id__lt=10)             # 獲取id小於10的值
    models.Tb1.objects.filter(id__lt=10, id__gt=1)   # 獲取id大於1 且 小於10的值

    in
    
    models.Tb1.objects.filter(id__in=[11, 22, 33])   # 獲取id等於十一、2二、33的數據
    models.Tb1.objects.exclude(id__in=[11, 22, 33])  # not in
    
    contains
    
    models.Tb1.objects.filter(name__contains="ven")
    models.Tb1.objects.filter(name__icontains="ven") # icontains大小寫不敏感
    models.Tb1.objects.exclude(name__icontains="ven")
    
    range
    
    models.Tb1.objects.filter(id__range=[1, 2])   # 範圍bettwen and
    
    其餘相似
    
    startswith,istartswith, endswith, iendswith,
    
    order by
    
    models.Tb1.objects.filter(name='seven').order_by('id')    # asc
    models.Tb1.objects.filter(name='seven').order_by('-id')   # desc
    
    limit 、offset
    
    models.Tb1.objects.all()[10:20]
    
    group by
    from django.db.models import Count, Min, Max, Sum
    models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))
    SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"
進階操做

三、連表操做(了不得的雙下劃線)

對象.query---------------------查看代碼的sql語句

利用雙下劃線和 _set 將表之間的操做鏈接起來

1 ,一對多

正向查找

from django.db import models
# Create your models here.

class UserType(models.Model):
    nid = models.AutoField(primary_key=True)
    caption = models.CharField(max_length=16)


class UserInfo(models.Model):
    user = models.CharField(max_length=32)
    email = models.EmailField(max_length=32)
    pwd = models.CharField(max_length=64)
    user_type = models.ForeignKey(UserType)
表結構實例
#不在filter()或values()中查詢使用
ret = models.UserInfo.objects.all()
for i in ret :
    print(type(i),i.user,i.user_type.caption)
#獲得的ret是一個queryset對象,只有咱們循環咱們獲得每一行的一個對象的時候才能夠用.字段名獲取數據
# 想獲取和其有聯繫表的數據的時候,i.user_type獲得的是一個有聯繫表的對象,咱們就能夠獲取數據了
#在filter()或values()中查詢使用
ret1 = models.UserInfo.objects.filter(user_type__caption='管理員').all().values('user','user_type__caption')
ret2 = models.UserInfo.objects.all().values('user','user_type__caption')
 
print(type(ret1),ret1)
print(type(ret2),ret2)
#咱們查的是userinfo表中的user,因此應該user中數據所有顯示,而'user_type__caption'即另外一張表中的數據根據user對應的值進行顯示

 反向查找

一、不在filter()或values()中查詢使用

ret = models.UserInfo.objects.all()
for i in ret :
    print(type(i.user_type),i.user_type)
 
ret1 = models.UserType.objects.all()
for j in ret1:
    print(type(j.userinfo_set),j.userinfo_set)
 
------------------------------------------------------------------------------------------------------------------------------------------------------
<class 'app1.models.UserType'> UserType object
<class 'app1.models.UserType'> UserType object
<class 'app1.models.UserType'> UserType object
 
<class 'django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager'> app1.UserInfo.None
<class 'django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager'> app1.UserInfo.None
<class 'django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager'> app1.UserInfo.None
 
------------------------------------------------------------------------------------------------------------------------------------------------------
一、以上咱們能夠看出有外鍵的類中存在user_type字段,能夠經過這個字段就能獲得和其對應表的對象,從而獲取另外一張表中的信息
二、而不存在外鍵的表中其實隱藏了一個userinfo_set字段,咱們一樣能夠經過這個字段獲取其對應表中的信息------->對應表表名_set

二、在filter()或values()中查詢使用

ret1 = models.UserType.objects.all().values('caption','userinfo')
ret2 = models.UserType.objects.all().values('caption','userinfo__user')
print(ret1)
print(ret2)
#若是反向查找的條件放到filter()或values()中的時候就不能用表名_set了,而用 ------>表名__

2 ,多對多

建立表的三種方式:

第三張表中自動生成聯合惟一索引

一、本身建立第三張關係表(適用於咱們在第三張表中自定義列)

class HostToGroup(models.Model):
    hgid = models.AutoField(primary_key=True)
    host_id = models.ForeignKey('Host')
    group_id = models.ForeignKey('Group')

class Host(models.Model):
    hid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32)
    ip = models.CharField(max_length=32)
class Group(models.Model):
    gid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16)
Host_TO_Group

2,經過ManyToManyField 來建立

class Host(models.Model):
    hid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32)
    ip = models.CharField(max_length=32)
class Group(models.Model):
    gid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16)

    h2g = models.ManyToManyField('Host')    #生成關係表
h2g

三、本身創第三種表+ManyToManyField()-----雖然這樣看起來後面的在建立數據庫的時候沒用,可是其在操做數據庫的時候有用

中間模型表若是是經過through制定的,add create方法會失效 

class Host_To_Group(models.Model):
    hg_id =models.AutoField(primary_key=True)
    host_id = models.ForeignKey('Host')      
    group_id = models.ForeignKey('Group')


class Host(models.Model):
    hid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32)
    ip = models.CharField(max_length=32)

class Group(models.Model):
    gid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)

    h2g = models.ManyToManyField('Host',through='Host_To_Group')  #這裏的through在操做數據庫的時候有用
g1 = models.Group.objects.get(gid=1)
h1 = models.Host.objects.get(hid=1)
h2 = models.Host.objects.filter(hid__gt=1)
# 正向添加數據
g1.h2g.add(h1)
g1.h2g.add(*h2)

h1 = models.Host.objects.get(hid=1)
g1 = models.Group.objects.get(gid=2)
g2 = models.Group.objects.filter(gid__gt=2)
# 反向添加數據
h1.group_set.add(g1)
h1.group_set.add(*g2)

g1 = models.Group.objects.get(gid=1)
h1 = models.Host.objects.get(hid=1)
h2 = models.Host.objects.filter(hid__gt=1)
# 正向刪除數據
g1.h2g.remove(h1)
g1.h2g.remove(*h2)

h1 = models.Host.objects.get(hid=1)
g1 = models.Group.objects.get(gid=2)
g2 = models.Group.objects.filter(gid__gt=2)
#反向刪除數據
h1.group_set.remove(g1)
h1.group_set.remove(*g2)

#正向查數據
h1 = models.Host.objects.get(hid=2)
print(h1.group_set)

#反向查數據
g1 = models.Group.objects.get(gid=2)
print(g1.h2g)

慎用:h1.group_set.all().delete()------------同時刪除關係表和關聯表中數據

 

以上若是咱們利用第三種方法創建表的時候,add、set等方法會失效,不能操做,只能查看

and  和 or

其中F表示可讓某一列的數據在當前的狀態下自增多少,而咱們平時用的updata只能把某一列數據都改變成同一個值

其中Q表示搜索條件能夠有or和and

# F 使用查詢條件的值
    #
    # from django.db.models import F
    # models.Tb1.objects.update(num=F('num')+1)
 
    # Q 構建搜索條件
    from django.db.models import Q
    # con = Q()
    #
    # q1 = Q()
    # q1.connector = 'OR'
    # q1.children.append(('id', 1))
    # q1.children.append(('id', 10))
    # q1.children.append(('id', 9))
    #
    # q2 = Q()
    # q2.connector = 'OR'
    # q2.children.append(('c1', 1))
    # q2.children.append(('c1', 10))
    # q2.children.append(('c1', 9))
    #
    # con.add(q1, 'AND')
    # con.add(q2, 'AND')
    #
    # models.Tb1.objects.filter(con)
 
    #
    # from django.db import connection
    # cursor = connection.cursor()
    # cursor.execute("""SELECT * from tb where name = %s""", ['Lennon'])
    # row = cursor.fetchone()

實例:

用Q 的條件搜索,查詢圖書的相關信息

from django.conf.urls import url
from django.contrib import admin
from app1 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^test/', views.test),
    url(r'^index/', views.index),
]
url
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .left{
            float: left;
        }
        .clearfix:after{  // 清除漂浮
            content: '.';
            clear: both;
            display: block;
            visibility: hidden;
            height: 0;
        }
    </style>
</head>
<body>
    <div class="condition">
        <div class="item clearfix">
            <div class="icon left" onclick="AddCondition(this);">+</div>
            <div class="left">
                <select onchange="ChangeName(this);">
                    <option value="name">書名</option>
                    <option value="book_type__caption">圖書類型</option>
                    <option value="price">價格</option>
                    <option value="pages">頁數</option>
                </select>
            </div>
            <div class="left"><input type="text" name="name" /></div>
        </div>
    </div>
    <div>
        <input type="button" onclick="Search();" value="搜索" />
    </div>

    <div class="container">

    </div>



    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        function  AddCondition(ths) {
            var new_tag = $(ths).parent().clone();  //複製父標籤
            new_tag.find('.icon').text('-');  // 在子孫中找,把內容改成「-」
            new_tag.find('.icon').attr('onclick', 'RemoveCondition(this);');  // (從新寫個事件)把以前綁定的增添事件更新成刪除

            $(ths).parent().parent().append(new_tag);  //添加
        }
        function  RemoveCondition(ths) {  // 刪除事件
            $(ths).parent().remove();
        }
        function ChangeName(ths) {  //修改內容觸發這個事件
            var v = $(ths).val();  //得到當前選中標籤的屬性
            $(ths).parent().next().find('input').attr('name',v);  //select標籤,父親的下一個標籤的input找出來,把屬性改成「v」
        }
        function Search() {  //搜索事件
            var post_data_dict = {};  //得到的值放在這個字典

            $('.condition input').each(function () {  // 獲取全部input的內容,循環一個個獲取;提交數據
                // console.log($(this)[0])   // ($(this)[0],是把Jquery對象轉變成DOM對象
                var n = $(this).attr('name');  //這裏的this是jQuery對象;獲取name屬性
                var v = $(this).val();  //獲取對象的值
                var v_list = v.split('');   // 利用分割,獲得輸入的多個內容
                post_data_dict[n] = v_list;  //把這些輸入值放到字典
            });
            console.log(post_data_dict);  //打印出


            var post_data_str = JSON.stringify(post_data_dict);  // 把post_data_dict這個字典轉換成字符串
            $.ajax({
                url: '/index/',  //這裏index後面必須加 "/"
                type: 'POST',
                data: { 'post_data': post_data_str},  // 要傳輸默認爲字符串,
                dataType: 'json',  //轉換類型
                success: function (arg) {
                    // 字符串 "<table>" +
                    if(arg.status){
                        var table = document.createElement('table');  // 成功的話把內容添加到table
                        table.setAttribute('border', 1);
                        // [{,name,pubdate,price,caption},]
                        $.each(arg.data, function(k,v){  //循環獲得返回的內容
                            var tr = document.createElement('tr');  //建立標籤

                            var td1 = document.createElement('td');  //建立標籤
                            td1.innerText = v['name'];  //標籤內容
                            var td2 = document.createElement('td');
                            td2.innerText = v['price'];
                            var td3 = document.createElement('td');
                            td3.innerText = v['book_type__caption'];
                            var td4 = document.createElement('td');
                            td4.innerText = v['pubdate'];
                            tr.appendChild(td1);  //標籤添加內容
                            tr.appendChild(td2);
                            tr.appendChild(td3);
                            tr.appendChild(td4);

                            table.appendChild(tr);
                            // 以上都是Dom建立標籤和添加標籤內容
                        });

                        $('.container').empty();  //加以前進行清空
                        $('.container').append(table);  //找到container把table添加進去
                    }else{
                        alert(arg.message);
                    }

                }

            })
        }
    </script>
</body>
</html>
html
from django.db import models

# Create your models here.


class Author(models.Model):
    """
    做者
    """
    name = models.CharField(max_length=100)
    age = models.IntegerField()


class BookType(models.Model):
    """
    圖書類型
    """
    caption = models.CharField(max_length=64)


class Book(models.Model):
    """
    圖書
    """
    name = models.CharField(max_length=64)
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    pubdate = models.DateField()

    # authors = models.ManyToManyField(Author)
    book_type = models.ForeignKey(BookType)

    def __str__(self):  # 獲取內容方便查看
        return 'obj:%s-%s' % (self.name, self.price)
models
from django.shortcuts import render,HttpResponse
from app01 import models
# Create your views here.
import json
def test(request):
    # models.BookType.objects.create(caption='技術')
    # models.BookType.objects.create(caption='文學')
    # models.BookType.objects.create(caption='動漫')
    # models.BookType.objects.create(caption='男人裝')

    # models.Book.objects.create(name='文藝復興',pages='100',price='40',pubdate='1992-11-2',book_type_id='1')
    # models.Book.objects.create(name='解密',pages='80',price='10', pubdate='2016-6-10',book_type_id='2')
    # models.Book.objects.create(name='刀鋒',pages='50',price='3', pubdate='2014-02-16',book_type_id='2')
    # models.Book.objects.create(name='查令十字路84號',pages='260',price='40',pubdate='1999-10-12',book_type_id='3')
    # models.Book.objects.create(name='紅樓',pages='1000',price='500', pubdate='1760-1-1',book_type_id='3')
    # models.Book.objects.create(name='將夜',pages='2000',price='300', pubdate='2010-3-3',book_type_id='1')
    # models.Book.objects.create(name='mysql從刪庫到跑路',pages='20',price='10',pubdate='1998-9-2',book_type_id='4')
    # models.Book.objects.create(name='馬克思主義',pages='50',price='100',pubdate='1937-3-3',book_type_id='2')

    return HttpResponse('ok')

import json
from datetime import date
from datetime import datetime
from decimal import Decimal

class JsonCustomEncoder(json.JSONEncoder):  #固定的格式模塊

    def default(self, field):

        if isinstance(field, datetime):
            return field.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(field, date):
            return field.strftime('%Y-%m-%d')
        elif isinstance(field, Decimal):
            return str(field)
        else:
            return json.JSONEncoder.default(self, field)

def index(request):
    if request.method == 'POST':
        ret = {'status': False, 'message': '', 'data':None}
        try:
            post_data = request.POST.get('post_data',None)
            post_data_dict = json.loads(post_data)   #反序列化
            print(post_data_dict)
            # {'name': ['11', 'sdf'],'price': ['11', 'sdf']}
            # 構造搜索條件
            from django.db.models import Q
            con = Q()
            for k,v in post_data_dict.items():
                q = Q()
                q.connector = 'OR'
                for item in v:
                    q.children.append((k, item))
                con.add(q, 'AND')
            """
            ret = models.Book.objects.filter(con)
            print(ret) # queryset,[對象]

            from django.core import serializers
            data = serializers.serialize("json", ret)
            print(type(data),data)
            # 字符串
            """
            """
            #ret = models.Book.objects.filter(con).values('name','book_type__caption')
            ret = models.Book.objects.filter(con).values_list('name', 'book_type__caption')
            print(ret,type(ret))
            li = list(ret)
            data = json.dumps(li)
            print(data,type(data))
            """
            result = models.Book.objects.filter(con).values('name','price','pubdate','book_type__caption')
            # ret = models.Book.objects.filter(con).values_list('name', 'book_type__caption')
            li = list(result)
            ret['status'] = True
            ret['data'] = li
        except Exception as e:
            ret['message'] = str(e)
        ret_str = json.dumps(ret, cls=JsonCustomEncoder)
        return HttpResponse(ret_str)
    return render(request, 'index.html')
Views
 
Dom對象與JQuery對象的相互轉換:
     document.getElementsTagName('div)[0]
 
jQuery對象
     $('div').first()
 
Dom對象轉換成JQuery對象:
     $(document.getElementsTagName('div)[0])  # 直接在Dom對象前加'$'
     
JQuery對象轉換成Dom對象:
     $('div').first()[0]  # 直在jQuery對象後加索引'[0]'
相關文章
相關標籤/搜索