Django 單表操做

orm介紹

查詢數據層次圖解:若是操做mysql,ORM是在pymysq之上又進行了一層封裝python

MVC或者MTV框架中包括一個重要的部分,就是ORM,它實現了數據模型與數據庫的解耦,即數據模型的設計不須要依賴於特定的數據庫,經過簡單的配置就能夠輕鬆更換數據庫,這極大的減輕了開發人員的工做量,不須要面對因數據庫變動而致使的無效勞動mysql

ORM是「對象-關係-映射」的簡稱。git

單表操做

在建立的名爲app01的項目下的models.py文件內建立模型:sql

from django.db import models

# Create your models here.
class Book(models.Model):
    id=models.AutoField(primary_key=True)
    name=models.CharField(max_length=32)
    price=models.DecimalField(max_digits=6,decimal_places=2)
    publish=models.CharField(max_length=32)
    author=models.CharField(max_length=32)
    create_date=models.DateField(null=True)
    def __str__(self):
        return '書名:%s,做者:%s,出版社:%s,價格:%s,出版時間:%s'%(self.name,self.author,self.publish,self.price,self.create_date)

字段參數

每一個字段有一些特有的參數,例如,CharField須要max_length參數來指定VARCHAR數據庫字段的大小。還有一些適用於全部字段的通用參數。 這些參數在文檔中有詳細定義數據庫

---字段---
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

    自定義無符號整數字段

        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)',

    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)
        - 二進制類型
---參數---
(1)null
若是爲True,Django 將用NULL 來在數據庫中存儲空值。 默認值是 False.
 
(1)blank
若是爲True,該字段容許不填。默認爲False。
要注意,這與 null 不一樣。null純粹是數據庫範疇的,而 blank 是數據驗證範疇的。
若是一個字段的blank=True,表單的驗證將容許該字段是空值。若是字段的blank=False,該字段就是必填的。
 
(2)default
字段的默認值。能夠是一個值或者可調用對象。若是可調用 ,每有新對象被建立它都會被調用。
 
(3)primary_key
若是爲True,那麼這個字段就是模型的主鍵。若是你沒有指定任何一個字段的primary_key=True,
Django 就會自動添加一個IntegerField字段作爲主鍵,因此除非你想覆蓋默認的主鍵行爲,
不然不必設置任何一個字段的primary_key=True。
 
(4)unique
若是該值設置爲 True, 這個數據字段的值在整張表中必須是惟一的
 
(5)choices
由二元組組成的一個可迭代對象(例如,列表或元組),用來給字段提供選擇項。 若是設置了choices ,默認的表單將是一個選擇框而不是標準的文本框,<br>並且這個選擇框的選項就是choices 中的選項。

配置

models.py模型建立好後 在settings.py須要進行數據庫的配置django

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'day76',
        'HOST':'127.0.0.1',
        'PORT':3306,
        'USER':'root',
        'PASSWORD':'admin'
    }
}
#'NAME':要鏈接的數據庫,鏈接前須要建立好,django不會建立數據庫
#'USER':鏈接數據庫的用戶名
#'PASSWORD':鏈接數據庫的密碼
#'HOST':鏈接主機,默認本機
#'PORT':端口 默認3306

接下來在項目下的_ _ init _ _.py文件內輸入app

import pymysql
pymysql.install_as_MySQLdb()

最後經過框架

python manage.py makemigrations
python manage.py migrate

這兩條命令便可在數據庫內建立表設計

表的操做

#插入數據的兩種方式
    # 方式一 :返回結果是一個對象
    book=models.Book.objects.create(name='紅樓夢',price=23.8,publish='人民出版社',author='曹雪芹',create_data='2018-09-17')
    # 方式二:先實例化產生對象,而後調用save方法,保存
    book=models.Book(name='水滸傳',price=99.8,publish='老男孩出版社',author='施耐庵',create_data='2018-08-08')
    book.save()
    print(book.name)
    # 時間格式,能夠傳字符串,能夠傳日期格式
    import datetime

    ctime = datetime.datetime.now()
    book = models.Book.objects.create(name='西遊記', price=73.8, publish='北京出版社', author='吳承恩', create_data=ctime)
    
#刪除
    # 刪除名字叫西遊記的這本書
    ret=models.Book.objects.filter(name='西遊記').delete()
    # 刪除的第二種方式:
    ret = models.Book.objects.filter(name='西遊記').first()
    ret.delete()
    
#修改
    ret=models.Book.objects.filter(name='西遊記').update(price=20.9)
    # 對象修改(沒有update方法,可是能夠用save來修改)
    book = models.Book.objects.filter(name='西遊記').first()
    book.price=89
    book.save()
    
#查詢
    (1)all()
    ret=models.Book.objects.all()
    print(ret)
    (2)filter()
    # 查詢名字叫西遊記的這本書
    ret=models.Book.objects.filter(name='西遊記').first()
    # 不支持負數,只支持正數
    ret=models.Book.objects.filter(name='西遊記')[-1]
    # filter內能夠傳多個參數,用逗號分隔,他們之間是and的關係
    ret=models.Book.objects.filter(name='西遊記',price='73.8')
    # ret.query -->queryset對象打印sql
    print(ret.query)
    # get() 有且只有一個結果,才能用,若是有一個,返回的是對象,不是queryset對象,一般用在,用id查詢的狀況
    ret=models.Book.objects.get(name='紅樓夢')
    ret=models.Book.objects.get(id=1)
    # exclude()查詢名字不叫西遊記的書,結果也是queryset對象
    ret=models.Book.objects.exclude(name='西遊記',price='23.8')
    #這裏是查詢 不是書名爲西遊記而且價格爲23.8的書 exclude把括號內的多個條件當成一個總體來進行查詢的
    # order_by 按價格升序排
    ret=models.Book.objects.all().order_by('price')
    # queryset對象能夠繼續 點 方法
    ret=models.Book.objects.all().order_by('price').filter(name='西遊記')
    # 按價格倒序排
    ret=models.Book.objects.all().order_by('-price')
    # 能夠傳多個
    ret=models.Book.objects.all().order_by('-price','create_data')
    # reverse 對結果進行反向排序
    ret=models.Book.objects.all().order_by('-price').reverse()
    # count  查詢結果個數
    ret=models.Book.objects.all().count()
    ret=models.Book.objects.all().filter(name='西遊記').count()
    # last 返回book對象
    ret=models.Book.objects.all().last()
    # exists 返回結果是布爾類型
    ret=models.Book.objects.filter(name='三國演義').exists()
    # values(*field): queryset對象裏套字典
    ret=models.Book.objects.all().values('name','price')
    ret=models.Book.objects.all().values('name')
    # value_list queryset對象裏套元組
    ret=models.Book.objects.all().values_list('name','price')
    # distinct() 必須徹底同樣,才能去重   只要帶了id,去重就沒有意義了
    ret=models.Book.objects.all().values('name').distinct()

基於雙下劃綫的模糊查詢

# 查詢價格大於89 的書
    ret=models.Book.objects.filter(price__gt='89')
    # 查詢價格小於89 的書
    ret=models.Book.objects.filter(price__lt='89')

    ret=models.Book.objects.filter(price__lt='89',price='89')
    # 小於等於
    ret=models.Book.objects.filter(price__lte='89')
    # 大於等於,
    ret = models.Book.objects.filter(price__gte='89')
    
    # in 在XX中
    ret=models.Book.objects.filter(price__in=['23.8','89','100'])

    # range 在XX範圍內 between and
    ret=models.Book.objects.filter(price__range=[50,100])

    # contains  查詢名字有'%紅%'的書
    ret=models.Book.objects.filter(name__contains='紅')

    # icontains 查詢名字帶p的書,忽略大小寫
    ret=models.Book.objects.filter(name__icontains='P')

    # startswith  以XX開頭
    ret=models.Book.objects.filter(name__startswith='紅')

    # endswith  以XX結尾
    ret=models.Book.objects.filter(name__endswith='夢')

    # pub_date__year 按年查詢 也有create_data__month  create_data__day
    ret=models.Book.objects.filter(create_data__year='2017')
相關文章
相關標籤/搜索