1. 程式人生 > >欄位和欄位的引數,查詢的13個方法,但標的雙下劃線外來鍵和多對多操作

欄位和欄位的引數,查詢的13個方法,但標的雙下劃線外來鍵和多對多操作

                欄位 

常用欄位 

AutoField()

自增列,必須填入引數 primary_key=True則成為資料庫的主鍵。無該欄位時,django自動建立 一個model不能有兩個AutoField欄位。

IntegerField()

一個整數型別。數值的範圍是 -2147483648 ~ 2147483647。

BooleanField()

布林值型別

CharField()

字元型別,必須提供max_length引數。max_length表示字元的長度。

TextField()

文字型別

DateTimeField 

日期時間欄位,格式為YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ],相當於Python中的datetime.datetime的例項。

DateField

日期型別,日期格式為YYYY-MM-DD,相當於Python中的datetime.date的例項。

引數:

  • auto_now:每次修改時修改為當前日期時間。
  • auto_now_add:新建立物件時自動添加當前日期時間。

auto_now和auto_now_add和default引數是互斥的,不能同時設定。

DecimalField

10進位制小數 引數: max_digits 小數總長度,decimal_places,小數位長度

 

欄位型別,詳情可點選查詢官網

AutoField(Field)
        - int自增列,必須填入引數 primary_key=True

    BigAutoField(AutoField)
        - bigint自增列,必須填入引數 primary_key=True

        注:當model中如果沒有自增列,則自動會建立一個列名為id的列
        from django.db import models

        class UserInfo(models.Model):
            
# 自動建立一個列名為id的且為自增的整數列 username = models.CharField(max_length=32) class Group(models.Model): # 自定義自增列 nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) SmallIntegerField(IntegerField): - 小整數 -32768 ~ 32767 PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField) - 正小整數 0 ~ 32767 IntegerField(Field) - 整數列(有符號的) -2147483648 ~ 2147483647 PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField) - 正整數 0 ~ 2147483647 BigIntegerField(IntegerField): - 長整型(有符號的) -9223372036854775808 ~ 9223372036854775807 BooleanField(Field) - 布林值型別 NullBooleanField(Field): - 可以為空的布林值 CharField(Field) - 字元型別 - 必須提供max_length引數, max_length表示字元長度 TextField(Field) - 文字型別 EmailField(CharField): - 字串型別,Django Admin以及ModelForm中提供驗證機制 IPAddressField(Field) - 字串型別,Django Admin以及ModelForm中提供驗證 IPV4 機制 GenericIPAddressField(Field) - 字串型別,Django Admin以及ModelForm中提供驗證 Ipv4和Ipv6 - 引數: 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中提供驗證 URL SlugField(CharField) - 字串型別,Django Admin以及ModelForm中提供驗證支援 字母、數字、下劃線、連線符(減號) CommaSeparatedIntegerField(CharField) - 字串型別,格式必須為逗號分割的數字 UUIDField(Field) - 字串型別,Django Admin以及ModelForm中提供對UUID格式的驗證 FilePathField(Field) - 字串,Django Admin以及ModelForm中提供讀取資料夾下檔案的功能 - 引數: path, 資料夾路徑 match=None, 正則匹配 recursive=False, 遞迴下面的資料夾 allow_files=True, 允許檔案 allow_folders=False, 允許資料夾 FileField(Field) - 字串,路徑儲存在資料庫,檔案上傳到指定目錄 - 引數: upload_to = "" 上傳檔案的儲存路徑 storage = None 儲存元件,預設django.core.files.storage.FileSystemStorage ImageField(FileField) - 字串,路徑儲存在資料庫,檔案上傳到指定目錄 - 引數: upload_to = "" 上傳檔案的儲存路徑 storage = None 儲存元件,預設django.core.files.storage.FileSystemStorage width_field=None, 上傳圖片的高度儲存的資料庫欄位名(字串) height_field=None 上傳圖片的寬度儲存的資料庫欄位名(字串) 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) - 長整數,時間間隔,資料庫中按照bigint儲存,ORM中獲取的值為datetime.timedelta型別 FloatField(Field) - 浮點型 DecimalField(Field) - 10進位制小數 - 引數: max_digits,小數總長度 decimal_places,小數位長度 BinaryField(Field) - 二進位制型別 欄位型別
欄位型別

            自定義欄位

自定義一個二進位制欄位,以及Django欄位與資料庫欄位型別的對應關係。

class UnsignedIntegerField(models.IntegerField):
    def db_type(self, connection):
        return 'integer UNSIGNED'

# PS: 返回值為欄位在資料庫中的屬性。
# Django欄位與資料庫欄位型別對應關係如下:
    '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)',
相信我你,不會想看的

自定義一個char型別欄位:

class MyCharField(models.Field):
    """
    自定義的char型別的欄位類
    """
    def __init__(self, max_length, *args, **kwargs):
        self.max_length = max_length
        super(MyCharField, self).__init__(max_length=max_length, *args, **kwargs)
 
    def db_type(self, connection):
        """
        限定生成資料庫表的欄位型別為char,長度為max_length指定的值
        """
        return 'char(%s)' % self.max_length

使用自定義char型別欄位:  

class Class(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=25)
    # 使用自定義的char型別的欄位
    cname = MyCharField(max_length=25)

建立的表結構:  

            欄位引數

 欄位引數,詳情可點選檢視官網

    null                資料庫中欄位是否可以為空
    db_column           資料庫中欄位的列名
    default             資料庫中欄位的預設值
    primary_key         資料庫中欄位是否為主鍵
    db_index            資料庫中欄位是否可以建立索引
    unique              資料庫中欄位是否可以建立唯一索引
    unique_for_date     資料庫中欄位【日期】部分是否可以建立唯一索引
    unique_for_month    資料庫中欄位【月】部分是否可以建立唯一索引
    unique_for_year     資料庫中欄位【年】部分是否可以建立唯一索引
 
    verbose_name        Admin中顯示的欄位名稱
    blank               Admin中是否允許使用者輸入為空
    editable            Admin中是否可以編輯
    help_text           Admin中該欄位的提示資訊
    choices             Admin中顯示選擇框的內容,用不變動的資料放在記憶體中從而避免跨表操作
                        如:gf = models.IntegerField(choices=[(0, '何穗'),(1, '大表姐'),],default=1)
 
    error_messages      自定義錯誤資訊(字典型別),從而定製想要顯示的錯誤資訊;
                        字典健:null, blank, invalid, invalid_choice, unique, and unique_for_date
                        如:{'null': "不能為空.", 'invalid': '格式錯誤'}
 
    validators          自定義錯誤驗證(列表型別),從而定製想要的驗證規則
                        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': '優先錯資訊1',
                                    'c2': '優先錯資訊2',
                                    'c3': '優先錯資訊3',
                                },
                                validators=[
                                    RegexValidator(regex='root_\d+', message='錯誤了', code='c1'),
                                    RegexValidator(regex='root_112233\d+', message='又錯誤了', code='c2'),
                                    EmailValidator(message='又錯誤了', code='c3'), ]
                            )
 

            Model Meta引數

這個不是很常用,如果你有特殊需要可以使用。詳情點選檢視官網。 

可以顯示中文

class UserInfo(models.Model):
    nid = models.AutoField(primary_key=True)
    username = models.CharField(max_length=32)
 
    class Meta:
        # 資料庫中生成的表名稱 預設 app名稱 + 下劃線 + 類名
        db_table = "table_name"
 
        # admin中顯示的表名稱
        verbose_name = '個人資訊'
 
        # verbose_name加s
        verbose_name_plural = '所有使用者資訊'
 
        # 聯合索引 
        index_together = [
            ("pub_date", "deadline"),   # 應為兩個存在的欄位
        ]
 
        # 聯合唯一索引
        unique_together = (("driver", "restaurant"),)   # 應為兩個存在的欄位
想看嗎,點我呀

                ORM操作

基本操作

# 增
models.Tb1.objects.create(c1='xx', c2='oo')   # 增加一條資料,可以接受字典型別資料 **kwargs
obj = models.Tb1(c1='xx', c2='oo')
obj.save()
 
 
# 查
models.Tb1.objects.get(id=123)  # 獲取單條資料,不存在則報錯(不建議)
models.Tb1.objects.all()  # 獲取全部
models.Tb1.objects.filter(name='seven')  # 獲取指定條件的資料
models.Tb1.objects.exclude(name='seven')  # 去除指定條件的資料
 
 
# 刪
# models.Tb1.objects.filter(name='seven').delete()  # 刪除指定條件的資料
 
 
# 改
models.Tb1.objects.filter(name='seven').update(gender='0')   # 將指定條件的資料更新,均支援 **kwargs
obj = models.Tb1.objects.get(id=1)
obj.c1 = '111'
obj.save()   # 修改單條資料    

                  查詢的13種方法

from app01 import model
# all() 獲取所有的資料 物件列表 ret = models.Person.objects.all() # filter() 獲取所有滿足條件的所有物件 物件列表 ret = models.Person.objects.filter(id=1) # get() 獲取一個物件 沒有或者是多個的時候報錯 ret = models.Person.objects.get(id=1) # exclude 獲取不滿足條件的所有物件 物件列表 ret = models.Person.objects.exclude(id=1) # values 獲取物件的欄位名和值 [ {},{} ] # 不指定欄位名 獲取所有欄位的名和值 # 指定欄位名 獲取指定欄位的名和值 ret = models.Person.objects.all().values('name','id') # for i in ret: # print(i,type(i)) # values_list 獲取物件的值 [ (),() ] # 不指定欄位名 獲取所有欄位的值 # 指定欄位名 獲取指定欄位值 ret = models.Person.objects.all().values_list('id','name') # for i in ret: # print(i,type(i)) # order_by 排序 預設升序 加- 降序 指定多個進行排序 ret = models.Person.objects.all().order_by('age','id') # reverse() 給已經排好序的結果倒敘排序 ret = models.Person.objects.all().order_by('age','id').reverse() ret = models.Person.objects.all().reverse() # distinct() 去重 # count 計數 ret = models.Person.objects.all().count() # first() last 取第一個 最後一個物件 ret = models.Person.objects.filter(id=100).first() # exists() 判斷資料是否存在 ret = models.Person.objects.filter(id=1).exists()
""" 返回結果是物件列表 all() filter() exclude() order_by() reverse() values() values_list() distinct() 返回結果是物件 get() first() last() 返回布林值 exists() 返回數字 count() """