2014年11月5日 星期三

Django筆記(5)-內建的 sqlite 資料庫


步驟一
填寫 helloWorld 目錄底下的 models.py (完整代碼如下)

#可以想成一個class將來會對應到一張資料表
#Django會自動對每個class加上id屬性

from django.db import models

class Vendor(models.Model):
    name = models.CharField(max_length=20)
    phone = models.CharField(max_length=15, blank=True) #blank允許資料留白

    #等等檢視資料時,以 name 辨識每筆資料
    def __str__(self):
        return self.name


class fruit(models.Model):
    name = models.CharField(max_length=20)
    price = models.DecimalField(max_digits=2,decimal_places=0)
    is_sweet = models.BooleanField(default=True)
    #decimal_places表示小數的顯示位數

    def __str__(self):
        return self.name

步驟二
切換到 mysite/,輸入以下的驗證指令
> python manage.py validate

若都沒問題會如下顯示
System check identified no issues (0 silenced).

步驟三
切換到 mysite/,輸入以下指令生成資料表
(過程中會詢問是否建立 superuser,先打 no 否定掉)
> python manage.py syncdb

查看被翻譯的資料庫語言
> python manage.py sqlall helloWorld

※發現必須刪除 helloWorld 目錄下的 migrations 目錄,否則上述指令和接下來的操作會報錯,原因不明

步驟四
切換到 mysite/,輸入以下指令進入 Django Shell,然後參照以下的資料庫語法自由練習
> python manage.py shell

#先引入資料庫模型
>>> from helloWorld.models import Vendor, fruit 


#新增


>>> Vendor.objects.create(name='AA', phone='1234')
>>> Vendor.objects.create(name='BB', phone='1432')
>>> fruit.objects.create(name='pomelo', price=20)
>>> fruit.objects.create(name='papaya', price=20)
>>> fruit.objects.create(name='grapes', price=15)


#刪除(演示的功能如下)


刪除表內的全部資料
刪除表內的一筆資料
>>> Vendor.objects.all().delete()
>>> Vendor.objects.filter(name='BB').delete()


#取得和打印資料


>>> Vendor.objects.all()
>>> data = Vendor.objects.all()
>>> data[0].name


#查找特定的資料(演示的功能如下)


可多個參數
可用欄位內的部分字串查找資料
可用字串開頭查找資料
可排除資料(包含多重排除)
限制條件查找資料
gt     對應的符號為  >
lt     對應的符號為  <
exact  對應的符號為  =
gte    對應的符號為 >=
lte    對應的符號為 <=
range  顧名思義
>>> Vendor.objects.filter(name='BB',phone='1234')
>>> Vendor.objects.filter(name__contains='Py')
>>> Vendor.objects.filter(name__startswith='B') 
>>> fruit.objects.filter(price__gt=15)
>>> fruit.objects.filter(price__lt=20)
>>> fruit.objects.filter(price__exact=15)
>>> fruit.objects.filter(price__gte=15)
>>> fruit.objects.filter(price__lte=15)
>>> fruit.objects.filter(price__range=(10,30))
>>> Vendor.objects.exclude(name='Python')
>>> Vendor.objects.exclude(name='BB').exclude(phone='1234')


#修改(演示的功能如下)


修改單筆資料的欄位
修改每一筆資料的欄位
>>> fruit.objects.all().update(price=60)
>>> fruit.objects.filter(name='grapes').update(price=50)


#排序(演示的功能如下)


正向排序
反向排序
多重條件排序
>>> fruit.objects.order_by('price')
>>> fruit.objects.order_by('-price')
>>> fruit.objects.order_by('price', 'name')


                                                                   上一篇    回目錄    下一篇

沒有留言:

張貼留言