Django --ORM常用的字段和参数 多对多创建形式
1 ORM字段
AutoField
int自增列,必須填入?yún)?shù) primary_key=True。當(dāng)model中如果沒有自增列,則自動會創(chuàng)建一個列名為id的列。
IntegerField
一個整數(shù)類型,范圍在 -2147483648 to 2147483647。
CharField
字符類型,必須提供max_length參數(shù), max_length表示字符長度。
DateField
日期字段,日期格式? YYYY-MM-DD,相當(dāng)于Python中的datetime.date()實(shí)例。
DateTimeField
日期時間字段,格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ],相當(dāng)于Python中的datetime.datetime()實(shí)例
常用和非常用字段
AutoField(Field)- int自增列,必須填入?yún)?shù) primary_key=TrueBigAutoField(AutoField)- bigint自增列,必須填入?yún)?shù) primary_key=True注:當(dāng)model中如果沒有自增列,則自動會創(chuàng)建一個列名為id的列from django.db import modelsclass 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 ~ 32767PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)- 正小整數(shù) 0 ~ 32767IntegerField(Field)- 整數(shù)列(有符號的) -2147483648 ~ 2147483647PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)- 正整數(shù) 0 ~ 2147483647BigIntegerField(IntegerField):- 長整型(有符號的) -9223372036854775808 ~ 9223372036854775807BooleanField(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)證 URLSlugField(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.FileSystemStorageImageField(FileField)- 字符串,路徑保存在數(shù)據(jù)庫,文件上傳到指定目錄- 參數(shù):upload_to = "" 上傳文件的保存路徑storage = None 存儲組件,默認(rèn)django.core.files.storage.FileSystemStoragewidth_field=None, 上傳圖片的高度保存的數(shù)據(jù)庫字段名(字符串)height_field=None 上傳圖片的寬度保存的數(shù)據(jù)庫字段名(字符串)DateTimeField(DateField)- 日期+時間格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]DateField(DateTimeCheckMixin, Field)- 日期格式 YYYY-MM-DDTimeField(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)制類型 View Code 'AutoField': 'integer AUTO_INCREMENT','BigAutoField': 'bigint AUTO_INCREMENT','BinaryField': 'longblob','BooleanField': 'bool','CharField': 'varchar(%(max_length)s)','CommaSeparatedIntegerField': 'varchar(%(max_length)s)','DateField': 'date','DateTimeField': 'datetime','DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)','DurationField': 'bigint','FileField': 'varchar(%(max_length)s)','FilePathField': 'varchar(%(max_length)s)','FloatField': 'double precision','IntegerField': 'integer','BigIntegerField': 'bigint','IPAddressField': 'char(15)','GenericIPAddressField': 'char(39)','NullBooleanField': 'bool','OneToOneField': 'integer','PositiveIntegerField': 'integer UNSIGNED','PositiveSmallIntegerField': 'smallint UNSIGNED','SlugField': 'varchar(%(max_length)s)','SmallIntegerField': 'smallint','TextField': 'longtext','TimeField': 'time','UUIDField': 'char(32)', ORM字段和數(shù)據(jù)庫字段的關(guān)系 2 ORM字段參數(shù)
null
用于表示某個字段可以為空。
unique
如果設(shè)置為unique=True 則該字段在此表中必須是唯一的 。
db_index
如果db_index=True 則代表著為此字段設(shè)置索引。
default
為該字段設(shè)置默認(rèn)值。
?DateField和DateTimeField
auto_now_add
配置auto_now_add=True,創(chuàng)建數(shù)據(jù)記錄的時候會把當(dāng)前時間添加到數(shù)據(jù)庫。
auto_now
配置上auto_now=True,每次更新數(shù)據(jù)記錄的時候會更新該字段。
null 數(shù)據(jù)庫中字段是否可以為空db_column 數(shù)據(jù)庫中字段的列名db_tablespacedefault 數(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ù)庫中字段【年】部分是否可以建立唯一索引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 自定義錯誤信息(字典類型),從而定制想要顯示的錯誤信息;字典健:null, blank, invalid, invalid_choice, unique, and unique_for_date如:{'null': "不能為空.", 'invalid': '格式錯誤'}validators 自定義錯誤驗(yàn)證(列表類型),從而定制想要的驗(yàn)證規(guī)則from django.core.validators import RegexValidatorfrom 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'), ]) ?
3 關(guān)系字段
ForeignKey
外鍵類型在ORM中用來表示外鍵關(guān)聯(lián)關(guān)系,一般把ForeignKey字段設(shè)置在 '一對多'中'多'的一方。
ForeignKey可以和其他表做關(guān)聯(lián)關(guān)系同時也可以和自身做關(guān)聯(lián)關(guān)系。
to
設(shè)置要關(guān)聯(lián)的表
to_field
設(shè)置要關(guān)聯(lián)的表的字段
related_name
反向操作時,使用的字段名,用于代替原反向查詢時的'表名_set'。
例如:
class Classes(models.Model):name = models.CharField(max_length=32)class Student(models.Model):name = models.CharField(max_length=32)theclass = models.ForeignKey(to="Classes")
當(dāng)我們要查詢某個班級關(guān)聯(lián)的所有學(xué)生(反向查詢)時,我們會這么寫:
models.Classes.objects.first().student_set.all()
當(dāng)我們在ForeignKey字段中添加了參數(shù)?related_name?后,
class Student(models.Model):name = models.CharField(max_length=32)theclass = models.ForeignKey(to="Classes", related_name="students")
當(dāng)我們要查詢某個班級關(guān)聯(lián)的所有學(xué)生(反向查詢)時,我們會這么寫:
models.Classes.objects.first().students.all()
related_query_name
反向查詢操作時,使用的連接前綴,用于替換表名。
on_delete
當(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) )?
db_constraint
是否在數(shù)據(jù)庫中創(chuàng)建外鍵約束,默認(rèn)為True。
OneToOneField
一對一字段。
通常一對一字段用來擴(kuò)展已有字段。
一對一的關(guān)聯(lián)關(guān)系多用在當(dāng)一張表的不同字段查詢頻次差距過大的情況下,將本可以存儲在一張表的字段拆開放置在兩張表中,然后將兩張表建立一對一的關(guān)聯(lián)關(guān)系。
class Author(models.Model):name = models.CharField(max_length=32)info = models.OneToOneField(to='AuthorInfo')class AuthorInfo(models.Model):phone = models.CharField(max_length=11)email = models.EmailField()
?
to
設(shè)置要關(guān)聯(lián)的表。
to_field
設(shè)置要關(guān)聯(lián)的字段。
on_delete
同F(xiàn)oreignKey字段。
ManyToManyField
用于表示多對多的關(guān)聯(lián)關(guān)系。在數(shù)據(jù)庫中通過第三張表來建立關(guān)聯(lián)關(guān)系
to
設(shè)置要關(guān)聯(lián)的表
related_name
同F(xiàn)oreignKey字段。
related_query_name
同F(xiàn)oreignKey字段。
symmetrical
僅用于多對多自關(guān)聯(lián)時,指定內(nèi)部是否創(chuàng)建反向操作的字段。默認(rèn)為True。
舉個例子:
class Person(models.Model):name = models.CharField(max_length=16)friends = models.ManyToManyField("self") 此時,person對象就沒有person_set屬性。
class Person(models.Model):name = models.CharField(max_length=16)friends = models.ManyToManyField("self", symmetrical=False) 此時,person對象現(xiàn)在就可以使用person_set屬性進(jìn)行反向查詢。
through
在使用ManyToManyField字段時,Django將自動生成一張表來管理多對多的關(guān)聯(lián)關(guān)系。
但我們也可以手動創(chuàng)建第三張表來管理多對多關(guān)系,此時就需要通過through來指定第三張表的表名。
through_fields
設(shè)置關(guān)聯(lián)的字段。
db_table
默認(rèn)創(chuàng)建第三張表時,數(shù)據(jù)庫中表的名稱。
4 多對多關(guān)聯(lián)關(guān)系的三種方式
方式一:自行創(chuàng)建第三張表
class Book(models.Model):title = models.CharField(max_length=32, verbose_name="書名")class Author(models.Model):name = models.CharField(max_length=32, verbose_name="作者姓名")# 自己創(chuàng)建第三張表,分別通過外鍵關(guān)聯(lián)書和作者
class Author2Book(models.Model):author = models.ForeignKey(to="Author")book = models.ForeignKey(to="Book")class Meta:unique_together = ("author", "book") 方式二:通過ManyToManyField自動創(chuàng)建第三張表
class Book(models.Model):title = models.CharField(max_length=32, verbose_name="書名")# 通過ORM自帶的ManyToManyField自動創(chuàng)建第三張表 class Author(models.Model):name = models.CharField(max_length=32, verbose_name="作者姓名")books = models.ManyToManyField(to="Book", related_name="authors")
方式三:設(shè)置ManyTomanyField并指定自行創(chuàng)建的第三張表
class Book(models.Model):title = models.CharField(max_length=32, verbose_name="書名")# 自己創(chuàng)建第三張表,并通過ManyToManyField指定關(guān)聯(lián)
class Author(models.Model):name = models.CharField(max_length=32, verbose_name="作者姓名")books = models.ManyToManyField(to="Book", through="Author2Book", through_fields=("author", "book"))# through_fields接受一個2元組('field1','field2'):# 其中field1是定義ManyToManyField的模型外鍵的名(author),field2是關(guān)聯(lián)目標(biāo)模型(book)的外鍵名。class Author2Book(models.Model):author = models.ForeignKey(to="Author")book = models.ForeignKey(to="Book")class Meta:unique_together = ("author", "book") ?
注意:
當(dāng)我們需要在第三張關(guān)系表中存儲額外的字段時,就要使用第三種方式。
但是當(dāng)我們使用第三種方式創(chuàng)建多對多關(guān)聯(lián)關(guān)系時,就無法使用set、add、remove、clear方法來管理多對多的關(guān)系了,需要通過第三張表的model來管理多對多關(guān)系。
5 元信息
ORM對應(yīng)的類里面包含另一個Meta類,而Meta類封裝了一些數(shù)據(jù)庫的信息。主要字段如下:
db_table
ORM在數(shù)據(jù)庫中的表名默認(rèn)是?app_類名,可以通過db_table可以重寫表名。
index_together
聯(lián)合索引。
unique_together
聯(lián)合唯一索引。
ordering
指定默認(rèn)按什么字段排序。
只有設(shè)置了該屬性,我們查詢到的結(jié)果才可以被reverse()。
舉例
class UserInfo(models.Model):nid = models.AutoField(primary_key=True)username = models.CharField(max_length=32)class Meta:# 數(shù)據(jù)庫中生成的表名稱 默認(rèn) app名稱 + 下劃線 + 類名db_table = "table_name"# 聯(lián)合索引index_together = [("pub_date", "deadline"),]# 聯(lián)合唯一索引unique_together = (("driver", "restaurant"),)ordering = ('name',)# admin中顯示的表名稱verbose_name='哈哈'# verbose_name加sverbose_name_plural=verbose_name
6 自定義字段(了解)
自定義char類型字段:
class FixedCharField(models.Field):"""自定義的char類型的字段類"""def __init__(self, max_length, *args, **kwargs):self.max_length = max_lengthsuper(FixedCharField, self).__init__(max_length=max_length, *args, **kwargs)def db_type(self, connection):"""限定生成數(shù)據(jù)庫表的字段類型為char,長度為max_length指定的值"""return 'char(%s)' % self.max_lengthclass Class(models.Model):id = models.AutoField(primary_key=True)title = models.CharField(max_length=25)# 使用自定義的char類型的字段cname = FixedCharField(max_length=25)
?
轉(zhuǎn)載于:https://www.cnblogs.com/polly-ling/p/9679163.html
總結(jié)
以上是生活随笔為你收集整理的Django --ORM常用的字段和参数 多对多创建形式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 海南白胡椒粉哪里最正宗?
- 下一篇: [NOI2005]聪聪与可可(期望dp)