參考資料:https://www.cnblogs.com/wupeiqi/articles/6216618.html
1 字段說明
AutoField(Field)
- int自增列,必須填入?yún)?shù) primary_key=True
BigAutoField(AutoField)
- bigint自增列,必須填入?yún)?shù) primary_key=True
注:當(dāng)model中如果沒有自增列,則自動會創(chuàng)建一個列名為id的列
from django.db import models
class UserInfo(models.Model):
# 自動創(chuàng)建一個列名為id的且為自增的整數(shù)列
username = models.CharField(max_length=32)
class Group(models.Model):
# 自定義自增列
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
SmallIntegerField(IntegerField):
- 小整數(shù) -32768 ~ 32767
PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
- 正小整數(shù) 0 ~ 32767
IntegerField(Field)
- 整數(shù)列(有符號的) -2147483648 ~ 2147483647
PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
- 正整數(shù) 0 ~ 2147483647
BigIntegerField(IntegerField):
- 長整型(有符號的) -9223372036854775808 ~ 9223372036854775807
BooleanField(Field)
- 布爾值類型
NullBooleanField(Field):
- 可以為空的布爾值
CharField(Field)
- 字符類型
- 必須提供max_length參數(shù), max_length表示字符長度
TextField(Field)
- 文本類型
EmailField(CharField):
- 字符串類型,Django Admin以及ModelForm中提供驗(yàn)證機(jī)制
IPAddressField(Field)
- 字符串類型,Django Admin以及ModelForm中提供驗(yàn)證 IPV4 機(jī)制
GenericIPAddressField(Field)
- 字符串類型,Django Admin以及ModelForm中提供驗(yàn)證 Ipv4和Ipv6
- 參數(shù):
protocol,用于指定Ipv4或Ipv6, 'both',"ipv4","ipv6"
unpack_ipv4, 如果指定為True,則輸入::ffff:192.0.2.1時候,可解析為192.0.2.1,開啟刺功能,需要protocol="both"
URLField(CharField)
- 字符串類型,Django Admin以及ModelForm中提供驗(yàn)證 URL
SlugField(CharField)
- 字符串類型,Django Admin以及ModelForm中提供驗(yàn)證支持 字母、數(shù)字、下劃線、連接符(減號)
CommaSeparatedIntegerField(CharField)
- 字符串類型,格式必須為逗號分割的數(shù)字
UUIDField(Field)
- 字符串類型,Django Admin以及ModelForm中提供對UUID格式的驗(yàn)證
FilePathField(Field)
- 字符串,Django Admin以及ModelForm中提供讀取文件夾下文件的功能
- 參數(shù):
path, 文件夾路徑
match=None, 正則匹配
recursive=False, 遞歸下面的文件夾
allow_files=True, 允許文件
allow_folders=False, 允許文件夾
FileField(Field)
- 字符串,路徑保存在數(shù)據(jù)庫,文件上傳到指定目錄
- 參數(shù):
upload_to = "" 上傳文件的保存路徑
storage = None 存儲組件,默認(rèn)django.core.files.storage.FileSystemStorage
ImageField(FileField)
- 字符串,路徑保存在數(shù)據(jù)庫,文件上傳到指定目錄
- 參數(shù):
upload_to = "" 上傳文件的保存路徑
storage = None 存儲組件,默認(rèn)django.core.files.storage.FileSystemStorage
width_field=None, 上傳圖片的高度保存的數(shù)據(jù)庫字段名(字符串)
height_field=None 上傳圖片的寬度保存的數(shù)據(jù)庫字段名(字符串)
DateTimeField(DateField)
- 日期+時間格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]
DateField(DateTimeCheckMixin, Field)
- 日期格式 YYYY-MM-DD
TimeField(DateTimeCheckMixin, Field)
- 時間格式 HH:MM[:ss[.uuuuuu]]
DurationField(Field)
- 長整數(shù),時間間隔,數(shù)據(jù)庫中按照bigint存儲,ORM中獲取的值為datetime.timedelta類型
FloatField(Field)
- 浮點(diǎn)型
DecimalField(Field)
- 10進(jìn)制小數(shù)
- 參數(shù):
max_digits,小數(shù)總長度
decimal_places,小數(shù)位長度
BinaryField(Field)
- 二進(jìn)制類型
2 字段參數(shù)
null 數(shù)據(jù)庫中字段是否可以為空
db_column 數(shù)據(jù)庫中字段的列名
default 數(shù)據(jù)庫中字段的默認(rèn)值
primary_key 數(shù)據(jù)庫中字段是否為主鍵 #主鍵也是索引,唯一且不能為空的
db_index 數(shù)據(jù)庫中字段是否可以建立索引 #索引為了加速查找
unique 數(shù)據(jù)庫中字段是否可以建立唯一索引 #加速查找和唯一限制
unique_for_date 數(shù)據(jù)庫中字段【日期】部分是否可以建立唯一索引
unique_for_month 數(shù)據(jù)庫中字段【月】部分是否可以建立唯一索引
unique_for_year 數(shù)據(jù)庫中字段【年】部分是否可以建立唯一索引
index_together = [
("pub_date", "deadline"),
] 聯(lián)合索引
unique_together = (("driver", "restaurant"),) 聯(lián)合唯一索引
verbose_name Admin中顯示的字段名稱
blank Admin中是否允許用戶輸入為空
editable Admin中是否可以編輯
help_text Admin中該字段的提示信息
choices Admin中顯示選擇框的內(nèi)容,用不變動的數(shù)據(jù)放在內(nèi)存中從而避免跨表操作
如:gf = models.IntegerField(choices=[(0, '何穗'),(1, '大表姐'),],default=1)
error_messages 自定義錯誤信息(字典類型),從而定制想要顯示的錯誤信息;
字典?。簄ull, blank, invalid, invalid_choice, unique, and unique_for_date
如:{'null': "不能為空.", 'invalid': '格式錯誤'}
validators 自定義錯誤驗(yàn)證(列表類型),從而定制想要的驗(yàn)證規(guī)則
from django.core.validators import RegexValidator
from django.core.validators import EmailValidator,URLValidator,DecimalValidator,\
MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
如:
test = models.CharField(
max_length=32,
error_messages={
'c1': '優(yōu)先錯信息1',
'c2': '優(yōu)先錯信息2',
'c3': '優(yōu)先錯信息3',
},
validators=[
RegexValidator(regex='root_\d+', message='錯誤了', code='c1'),
RegexValidator(regex='root_112233\d+', message='又錯誤了', code='c2'),
EmailValidator(message='又錯誤了', code='c3'), ]
)
2.1 ForeignKey中字段參數(shù)說明
ForeignKey(ForeignObject) # ForeignObject(RelatedField)
to, # 要進(jìn)行關(guān)聯(lián)的表名
to_field=None, # 要關(guān)聯(lián)的表中的字段名稱
on_delete=None, # 當(dāng)刪除關(guān)聯(lián)表中的數(shù)據(jù)時,當(dāng)前表與其關(guān)聯(lián)的行的行為
- models.CASCADE,刪除關(guān)聯(lián)數(shù)據(jù),與之關(guān)聯(lián)也刪除
- models.DO_NOTHING,刪除關(guān)聯(lián)數(shù)據(jù),引發(fā)錯誤IntegrityError
- models.PROTECT,刪除關(guān)聯(lián)數(shù)據(jù),引發(fā)錯誤ProtectedError
- models.SET_NULL,刪除關(guān)聯(lián)數(shù)據(jù),與之關(guān)聯(lián)的值設(shè)置為null(前提FK字段需要設(shè)置為可空)
- models.SET_DEFAULT,刪除關(guān)聯(lián)數(shù)據(jù),與之關(guān)聯(lián)的值設(shè)置為默認(rèn)值(前提FK字段需要設(shè)置默認(rèn)值)
- models.SET,刪除關(guān)聯(lián)數(shù)據(jù),
a. 與之關(guān)聯(lián)的值設(shè)置為指定值,設(shè)置:models.SET(值)
b. 與之關(guān)聯(lián)的值設(shè)置為可執(zhí)行對象的返回值,設(shè)置:models.SET(可執(zhí)行對象)
def func():
return 10
class MyModel(models.Model):
user = models.ForeignKey(
to="User",
to_field="id"
on_delete=models.SET(func),)
related_name=None, # 反向操作時,使用的字段名,用于代替 【表名_set】 如: obj.表名_set.all()
related_query_name=None, # 反向操作時,使用的連接前綴,用于替換【表名】 如: models.UserGroup.objects.filter(表名__字段名=1).values('表名__字段名')
limit_choices_to=None, # 在Admin或ModelForm中顯示關(guān)聯(lián)數(shù)據(jù)時,提供的條件:
# 如:
- limit_choices_to={'nid__gt': 5}
- limit_choices_to=lambda : {'nid__gt': 5}
from django.db.models import Q
- limit_choices_to=Q(nid__gt=10)
- limit_choices_to=Q(nid=8) | Q(nid__gt=10)
- limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')
db_constraint=True # 是否在數(shù)據(jù)庫中創(chuàng)建外鍵約束,默認(rèn)為true
parent_link=False # 在Admin中是否顯示關(guān)聯(lián)數(shù)據(jù)
2.2 OneToOneField中字段參數(shù)說明
OneToOneField(ForeignKey) #OneToOne繼承于ForeignKey
to, # 要進(jìn)行關(guān)聯(lián)的表名
to_field=None # 要關(guān)聯(lián)的表中的字段名稱
on_delete=None, # 當(dāng)刪除關(guān)聯(lián)表中的數(shù)據(jù)時,當(dāng)前表與其關(guān)聯(lián)的行的行為
###### 對于一對一 ######
# 1. 一對一其實(shí)就是 一對多 + 唯一索引
# 2.當(dāng)兩個類之間有繼承關(guān)系時,默認(rèn)會創(chuàng)建一個一對一字段
# 如下會在A表中額外增加一個c_ptr_id列且唯一:
class C(models.Model):
nid = models.AutoField(primary_key=True)
part = models.CharField(max_length=12)
class A(C):
id = models.AutoField(primary_key=True)
code = models.CharField(max_length=1)
2.3 ManyToManyField中字段參數(shù)說明
ManyToManyField(RelatedField)
to, # 要進(jìn)行關(guān)聯(lián)的表名,默認(rèn)與表的主鍵關(guān)聯(lián)
related_name=None, # 反向操作時,使用的字段名,用于代替 【表名_set】 如: obj.表名_set.all()
related_query_name=None, # 反向操作時,使用的連接前綴,用于替換【表名】 如: models.UserGroup.objects.filter(表名__字段名=1).values('表名__字段名')
limit_choices_to=None, # 在Admin或ModelForm中顯示關(guān)聯(lián)數(shù)據(jù)時,提供的條件:
# 如:
- limit_choices_to={'nid__gt': 5}
- limit_choices_to=lambda : {'nid__gt': 5}
from django.db.models import Q
- limit_choices_to=Q(nid__gt=10)
- limit_choices_to=Q(nid=8) | Q(nid__gt=10)
- limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')
symmetrical=None, # 僅用于多對多自關(guān)聯(lián)時,symmetrical用于指定內(nèi)部是否創(chuàng)建反向操作的字段
# 做如下操作時,不同的symmetrical會有不同的可選字段
models.BB.objects.filter(...)
# 可選字段有:code, id, m1
class BB(models.Model):
code = models.CharField(max_length=12)
m1 = models.ManyToManyField('self',symmetrical=True)
# 可選字段有: bb, code, id, m1
class BB(models.Model):
code = models.CharField(max_length=12)
m1 = models.ManyToManyField('self',symmetrical=False)
through=None, # 自定義第三張表時,使用字段用于指定關(guān)系表
through_fields=None, # 自定義第三張表時,使用字段用于指定關(guān)系表中那些字段做多對多關(guān)系表
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=50)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(
Person,
through='Membership',
through_fields=('group', 'person'),
)
class Membership(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
inviter = models.ForeignKey(
Person,
on_delete=models.CASCADE,
related_name="membership_invites",
)
invite_reason = models.CharField(max_length=64)
db_constraint=True, # 是否在數(shù)據(jù)庫中創(chuàng)建外鍵約束
db_table=None, # 默認(rèn)創(chuàng)建第三張表時,數(shù)據(jù)庫中表的名稱,默認(rèn)為AtoB
3 數(shù)據(jù)庫操作總結(jié)
.all
.values
.values_list
.delete
.filter
.update
.create
.m.add
.m.set
.m.clear
.m.remove
.only
.defer
.extra
.raw
.select_related('跨表字段') #:一次連表查詢獲取所有的數(shù)據(jù),如UserInfo.objects.select_related('ut') 連表查詢性能低
.prefetch_related #prefetch_related的性能高,有選擇的獲取 UserInfo.objects.prefetch_related('ut')
# select * from userinfo where id < 20
# 計(jì)算獲取到的所有用戶的用戶類型ID [1,]
# select * from usertype where id in [1,]
3.1 自己寫SQL的方式
# from django.db import connection, connections
# cursor = connection.cursor() # cursor = connections['default'].cursor()
# cursor.execute("""SELECT * from auth_user where id = %s""", [1])
# row = cursor.fetchone()
models.UserInfo.objects.raw('select id,name from userinfo')
Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))