所有Django模型繼承<django.db.models.Model>類
通過(guò)類屬性定義模型字段,如:models.XXField
通過(guò)模型類中的Meta子類定義模型元數(shù)據(jù)(非字段的其他數(shù)據(jù))官帘,如:數(shù)據(jù)庫(kù)表名,數(shù)據(jù)默認(rèn)排序方式
常見Meta類屬性:
- abstract:True or False滴铅,標(biāo)志本類是不是抽象基類
- app_label:定義本類所屬的應(yīng)用邻吭,如 app_label='myapp'
- db_table:映射的數(shù)據(jù)表名探遵,如:db_table='moment'
- db_tablespace:映射的表空間名稱淌喻,只存在某些數(shù)據(jù)庫(kù)如Oracle中
- default_related_name:定義本模型的反向關(guān)系引用名稱
- get_latest_by:定義按哪個(gè)字段值排列以獲得模型的開始或結(jié)束記錄
- managed:True or False盛险,定義Django的manage.py命令行工具是否管理本模型
- order_with_respect_to:定義本模型可以按照某外鍵引用的關(guān)系排序
- ordering:默認(rèn)為升序瞄摊,字段前加上'-'為降序
- default_permissions:模型操作權(quán)限,默認(rèn)為 =('add', 'change', 'delete')
- proxy:True or False苦掘,本模型及所有繼承自本模型的子模型是否為代理模型
- required_db_features:定義底層數(shù)據(jù)庫(kù)所必須具備的特性
- required_db_vendor:定義底層數(shù)據(jù)庫(kù)的類型换帜,如 MySQL、Oracle
- unique_together:用來(lái)設(shè)置的不重復(fù)的字段組合鹤啡,必須唯一
- index_together:定義聯(lián)合索引的字段惯驼,可以設(shè)置多個(gè)
- verbose_name:指明一個(gè)易于理解和表述的單數(shù)形式的對(duì)象名稱,如果該值沒(méi)有設(shè)置递瑰,對(duì)象的表述名為對(duì)象名的小寫分詞形式祟牲,如 CamelCase——> camel case
- verbose_name_plural:指明一個(gè)易于理解和表述的復(fù)數(shù)形式的對(duì)象名稱
普通字段是指模型類中除外鍵關(guān)系外的數(shù)據(jù)字段屬性,提供以下信息:
- 在數(shù)據(jù)庫(kù)中用什么類型定義模型字段
- 用什么樣的HTML標(biāo)簽顯示模型字段
- 需要什么樣的HTML表單數(shù)據(jù)驗(yàn)證
常用普通字段:
- AutoField:通常只用于充當(dāng)數(shù)據(jù)表的主鍵泣矛,沒(méi)有定義此項(xiàng)時(shí)疲眷,會(huì)自動(dòng)生成
- BigIntegerField:64位整型字段
- BinaryField:二進(jìn)制數(shù)據(jù)字段
- BooleanField:布爾字段
- CharField:字符串字段
- TextField:大容量文本字段
- CommaSeparatedIntegerField:用于存放逗號(hào)分隔的整數(shù)值
- DateField:日期字段
- DateTimeField:類似于DateField,但同時(shí)支持時(shí)間的輸入
- DurationField:存儲(chǔ)時(shí)間周期
- EmailField:一個(gè)檢查Email合法性的CharField
- FileField:一個(gè)文件上傳字段您朽,必須傳入?yún)?shù)upload_to狂丝,即上傳路徑
- FilePathField:按目錄限制規(guī)則選擇文件,必須傳入?yún)?shù)path
- FloatField:浮點(diǎn)型字段
- ImageField:一個(gè)圖片上傳字段哗总,同時(shí)會(huì)驗(yàn)證圖片合法性几颜,可選參數(shù)height_field、width_field讯屈,要求安裝Python Imaging庫(kù)
- IntegerField:用于保存整數(shù)
- IPField:一個(gè)字符串形式的IP地址
- NullBooleanField:類似BooleanField蛋哭,但多了None選項(xiàng)
- PhoneNumberField:帶美國(guó)風(fēng)格的電話校驗(yàn)的CharField
- PositiveIntegerField:只能輸入非負(fù)數(shù)的IntegerField
- SlugField:只包含字母、數(shù)字涮母、下劃線和連字符的輸入字段谆趾,通常用于URL
- SmallIntegerField:類似于IntegerField躁愿,適合較小的整數(shù)
- TimeField:時(shí)間字段,類似DateTimeField沪蓬,但只能表達(dá)和輸入時(shí)間
- URLField:用于保存URL
- USStateField:美國(guó)州名的縮寫字段
- XMLField:XML字符字段彤钟,是具有XML合法性驗(yàn)證的TextField
常用字段參數(shù):
- null:定義是否允許相對(duì)應(yīng)的數(shù)據(jù)庫(kù)字段為null,默認(rèn)值為False跷叉,數(shù)據(jù)庫(kù)中的非空約束
- blank:定義字段是否可以為空逸雹,HTML表達(dá)驗(yàn)證
- choices:定義字段的可選值
- default:設(shè)定默認(rèn)值
- help_text:HTML頁(yè)面中輸入空間的幫助字符串
- primary_key:定義字段是否為主鍵
- unique:是否為字段定義數(shù)據(jù)庫(kù)的唯一約束
基本查詢:
Django通過(guò)模型的objects對(duì)象實(shí)現(xiàn)模型數(shù)據(jù)查詢
過(guò)濾器:
- filter(**kwargs):返回符合篩選結(jié)果的數(shù)據(jù)集:
X.objects.filter(pub_date__year=2015)
- exclude(**kwargs):返回不符合篩選結(jié)果的數(shù)據(jù)集:
X.objects.filter(pub_date__year=2015).exclude(pub_date__month=1)
PS:兩者可以結(jié)合使用
Django獨(dú)特的字段查詢(filed lookup):字段名稱__謂詞(雙下滑線)
字段查詢謂詞:X.objects.filter.
- exact:精確等于 (id__exact=1)
- iexact:大小寫不敏感等于 (headline__iexact='I like this')
- contains:模糊匹配 (headline__contains='good')
- in: 包含 (id__in[1, 5, 9])
- gt: 大于 (n_visit__gt=30)
- gte: 大于等于
- lt: 小于
- lte: 小于等于
- startswith: 以...開頭 (body_text__startswith='Hello')
- endswith: 以...結(jié)尾
- range: 在...范圍內(nèi) (pub_date__range=(start_date, end_date))
- year: 年
- month: 月
- day: 日
- week_day:星期幾
- isnull:是否為空
還提供 - get()查詢單條記錄:x.objects.get(id_exact=1)
- 類似于切片的操作:x.objects.all()[:10]
- order_by操作:x.objects.order_by('name')
數(shù)據(jù)保存與刪除:
定義了統(tǒng)一的save(),用于完成模型的 Insert 和 Update 操作
定義了delete()用于刪除記錄
關(guān)系操作:
利用數(shù)據(jù)表之間的關(guān)系進(jìn)行數(shù)據(jù)建模和業(yè)務(wù)開發(fā)是關(guān)系數(shù)據(jù)庫(kù)最主要的功能
1云挟、一對(duì)一關(guān)系(OneToOneField)
from django.db import models
class Account(models.Model):
user_name = models.CharField(max_lenght=80)
password = models.CharField(max_length=255)
reg_date = models.DateField()
# __unicode__()函數(shù)用于定義模型的顯示字符串
def __unicode__(self):
return 'Account: %s' % self.user_name
class Contact(models.Model):
# on_delete參數(shù)定義當(dāng)被關(guān)聯(lián)模型的記錄被刪除時(shí)本模型的記錄如何處理
# models.CASCADE用于定義本記錄也被刪除
account = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True)
zip_code = models.CharField(max_length=10)
address = models.CharField(max_length=80)
mobile = model.CharField(max_length=20)
def __unicode__(self):
return '%s %s' % (self.account.user_name, mobile)
2梆砸、一對(duì)多關(guān)系
from django.db import models
class Account(models.Model):
user_name = models.CharField(max_lenght=80)
password = models.CharField(max_length=255)
reg_date = models.DateField()
def __unicode__(self):
return 'Account: %s' % self.user_name
class Contact(models.Model):
account = models.ForeignKey(Account, on_delete=models.CASCADE, primary_key=True)
zip_code = models.CharField(max_length=10)
address = models.CharField(max_length=80)
mobile = model.CharField(max_length=20)
def __unicode__(self):
return '%s %s' % (self.account.user_name, mobile)
3、多對(duì)多關(guān)系
from django.db import models
class Account(models.Model):
user_name = models.CharField(max_lenght=80)
password = models.CharField(max_length=255)
reg_date = models.DateField()
def __unicode__(self):
return 'Account: %s' % self.user_name
class Contact(models.Model):
account = models.ManyToManyField(Account)
zip_code = models.CharField(max_length=10)
address = models.CharField(max_length=80)
mobile = model.CharField(max_length=20)
def __unicode__(self):
return '%s %s' % (self.account.user_name, mobile)
面向?qū)ο驩RM:
Django支持三種風(fēng)格的模型繼承
1园欣、抽象類繼承:父類繼承自models.Model帖世,但不會(huì)在底層數(shù)據(jù)庫(kù)生成相應(yīng)的數(shù)據(jù)表
from django.db import models
class MessageBase(models.Model):
id = models.AutoField()
content = models.CharField(max_length=100)
user_name = models.CharField(max_length=80)
pub_date = models.DateField()
class Meta:
abstract = True
class Moment(MessageBase):
headline = models.CharField(max_length=50)
LEVELS = (
('1', 'Very good')
('2', 'Good')
('3', 'Normal')
('4', 'Bad')
)
class Coment(MessageBase):
level = models.CharField(max_length=1, choices=LEVELS)
遷移數(shù)據(jù)后,會(huì)定義兩個(gè)數(shù)據(jù)表:
數(shù)據(jù)表 Moment:有id俊庇、content狮暑、user_name、pub_date辉饱、headline
數(shù)據(jù)表 Comment:有id、content拣展、user_name彭沼、pub_date、level
2备埃、多表繼承:每個(gè)模型都在數(shù)據(jù)庫(kù)中生成相應(yīng)的數(shù)據(jù)表管理數(shù)據(jù)姓惑,父類中的字段不會(huì)重復(fù)地在多個(gè)子類的相關(guān)數(shù)據(jù)表中定義,從這個(gè)意義講按脚,多表繼承才是真正的面向?qū)ο蟮腛RM技術(shù)
from django.db import models
class MessageBase(models.Model):
id = models.AutoField()
content = models.CharField(max_length=100)
user_name = models.CharField(max_length=80)
pub_date = models.DateField()
class Moment(MessageBase):
headline = models.CharField(max_length=50)
class Coment(MessageBase):
level = models.CharField(max_length=1, choices=LEVELS)
遷移數(shù)據(jù)后于毙,會(huì)定義三個(gè)數(shù)據(jù)表:
數(shù)據(jù)表 Moment:有id、headline
數(shù)據(jù)表 Comment:有id辅搬、level
數(shù)據(jù)表 MessageBase:有id唯沮、content、user_name堪遂、pub_date
PS:在子類實(shí)例中可以通過(guò)小寫的父類的名字可以引用父類的實(shí)力
m1 = Moment(user_name='Terry', headline='Hello World')
print m1.messagebase.user_name
3介蛉、代理模型繼承:父類用于在底層數(shù)據(jù)庫(kù)中管理數(shù)據(jù)表,而子類不定義數(shù)據(jù)列溶褪,只定義查詢數(shù)據(jù)集的排序方式等元數(shù)據(jù)
from django.db import models
class Moment(models.Model):
id = models.AutoField()
headline = models.CharField(max_length=50)
content = models.CharField(max_length=100)
user_name = models.CharField(max_length=80)
pub_date = models.DateField()
class OrderedMoment(Moment):
class Meta:
proxy = True
ordering = ['-pub_date']
使用代理模型繼承的原因是子類中新的特性不會(huì)影響父類模型及其已有代碼的行為