Python筆記(六)- 模型及Django網站管理

來源:互聯網
上載者:User

標籤:

  在這篇博文中,將介紹django與資料庫方面的互動的知識。首先在網上下載Python For MySQL,然後進行安裝。安裝成功之後,在setting.py檔案中進行裝載,如下:

 1 DATABASES = { 2     ‘default‘: { 3         ‘ENGINE‘: ‘django.db.backends.mysql‘, 4         ‘NAME‘: ‘database‘, #首先要在MySQL中建立一個資料庫叫database 5         ‘USER‘:‘root‘,  #你資料庫的使用者 6         ‘PASSWORD‘:‘root‘,  #你資料庫的密碼 7         ‘HOST‘:‘127.0.0.1‘, 8         ‘PORT‘:‘3306‘ 9     }10 }

  配置好之後,如果沒有錯的話,進入項目所在目錄,在命令列中運行python manage.py shell來進行測試。如果輸入下面這段代碼沒有顯示什麼錯誤資訊,就證明你的資料庫配置正確了。之後就能進行增刪改查操作。

1 from django.db import connection2 cursor = connection.cursor()

  下面假設你的資料庫配置正確了。我們將示範如何進行增刪改查操作。

  首先在app應用中添加模型,我這裡添加了3個,分別如下:

 1 #encoding=utf-8 2 from django.db import models 3  4 #建立模型,對應MySQL中的表 5 # Create your models here. 6      7 class Publisher(models.Model): 8     name = models.CharField(max_length = 30)    #欄位名以及類型指定 9     address = models.CharField(max_length = 50)10     city = models.CharField(max_length = 50)11     state_province = models.CharField(max_length = 50)12     country = models.CharField(max_length = 50,blank=True)#blank=True表明欄位可以為空白13     website = models.URLField(blank=True) #Python提供的特定URL形式14     15     def __unicode__(self):  #相當於Java中的toString()16         return u‘id=%d,name=%s‘%(self.id,self.name)17     18     class Meta: #指定之後查出的結果集按照id的升序排列,使用ordering=[‘-id‘]則為降序.19         ordering = [‘id‘]20         21 class Author(models.Model):22     first_name = models.CharField(max_length = 50)23     last_name = models.CharField(max_length = 50)24     email = models.EmailField() #Python提供的特定Email格式x25     26     def __unicode__(self):27         return u‘firstname=%s‘ %self.first_name28     29     class Meta:30         ordering = [‘id‘]31     32 class Book(models.Model):33     title = models.CharField(max_length = 50)34     author = models.ManyToManyField(Author) #book和author為多對多35     publisher = models.ForeignKey(Publisher)#外鍵36     publication_date = models.DateField()   #Python提供的特定日期格式37     38     def __unicode__(self):39         return self.title40     41     class Meta:42         ordering = [‘id‘]

  上面的代碼請參看其後注釋,很容易理解。簡曆好模型之後(模型對應我們在資料庫中表),我們在setting.py中的INSTALLED_APPS元組裡對我們的項目進行註冊。然後使用python manage.py syncdb命令建立資料庫中的表。建立成功之後,在tests.py裡面對資料庫進行操作(不是一定要在這個檔案裡)。

  插入資料

  先看下面這段代碼:

 1 #encoding=utf-8 2 #Create your tests here. 3 from Second.models import Publisher 4 #插入對象 5 p1 = Publisher(name=‘zhouxy‘,address=‘nenu-software‘,city=‘長春‘,state_province=‘CA‘,country=‘China‘,website=‘www.cnblogs.com/zhouxuanyu‘) 6 p1.save(); 7 p2 = Publisher(name=‘zhouxuanyu‘,address=‘nenu-software‘,city=‘長春‘,state_province=‘CA‘,country=‘China‘,website=‘www.cnblogs.com/zxyyxzshine‘) 8 p2.save(); 9 publisher_list = Publisher.objects.all();10 print publisher_list

  在上面第5,7行建立兩個對象p1,p2。然後我們分別調用它們的save()方法,將其插入資料庫。9,10行列印出這兩個對象的資訊。列印的資訊就是我們在model中定義Publisher的時候所定義的__unicode__函數返回的值。類似於Java中對象的toString()。下面是結果圖:

  我們可以使用python manage.py sqlall Second命令來顯示MySQL文法。(版面原因,我只截部分圖)

  查詢資料

1 #查詢對象2 print Publisher.objects.filter(name=‘zhouxy‘).order_by(‘id‘) #等同於在sql中使用where關鍵字,也可以在model中添加class Meta:3 print Publisher.objects.filter(name=‘zhouxy‘,city=‘長春‘) #等同於在sql中使用where和and關鍵字4 print Publisher.objects.filter(name__contains=‘zhouxy‘)[0:2] #sql預設=操作符是精確匹配,欄位__contains相當於sql中的like,切片操作符等同於sql中的offset..limit..5 print Publisher.objects.get(name=‘zxyyxzshine‘,id=2) #擷取單個對象

  對照注釋,很容易理解。filter()等同於sql中的where關鍵字。order_by()等同於sql中的order by語句。如果在filter中添加一個以上的條件,那麼就相當於在sql中在條件陳述式中使用and關鍵字將條件結合起來。

  更新資料

1 #更新對象2 print Publisher.objects.filter(id=1).update(name="zxyyxzshine") #返回更新成功的row數3 print Publisher.objects.filter(name=‘zhouxuanyu‘).update(name=‘zxyyxzshine‘)

  刪除對象

1 #刪除對象2 print Publisher.objects.filter(id=1).delete()  3 print Publisher.objects.all().delete()

 

Python筆記(六)- 模型及Django網站管理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.