python+Django框架運用(三)

Django模型

模式指的是根據數據庫中數據表的結構來建立出來的class,每一張表到Python中就是一個html

class,表中的每個列,到Python中就是class的一個屬性。mysql

在模型中能夠完成對數據庫的增刪改查操做sql

建立和使用模型 --ORM(對象關係映射)

三大特徵:數據庫

  一、數據表到類的映射django

    將數據表自動生成一個class類服務器

    同時也能夠將一個class類自動生成一張數據表函數

  二、數據類型的映射url

    能夠將表中的字段數據類型字段映射到Python中對應的數據類型spa

    反之一樣code

  三、關係映射

    在Python中能夠將表與表之間的關係映射出來

    表與表之間的關係也能夠自動映射到Python中的class

    數據表之間的關聯關係:一對1、一對多、多對多

 

建立和配置數據庫

一、先在數據庫中建立一個庫(mysql)

  create database 庫名 default utf8;

二、配置數據庫(在Django項目中settings.py中)

 

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  #引擎
        'NAME': 'myitem',    # 庫名
        'USER': 'laige',  # 用戶名
        'PASSWORD': '123456',  # 密碼
        'HOST': '172.16.2.178',  # 數據庫服務器地址
        'PORT': 3306,  # 端口
    }
}        

Django中鏈接Mysql須要依賴於pymysql,在項目主目錄中__init__.py增長:

import pymysql
pymysql.install_as_MySQLdb()

編寫Models

在應用的models.py文件中定義與數據表對應的class

文件中的每一個class類都稱爲模型類、實體類,每一個實體類必須繼承自models.Model

from django.db import models


# 定義一個實體類Users
class Users(models.Model):
    # 對應數據表中name字段,數據類型varchar(20)
    name = models.CharField(max_length=20)
    # 對應數據表中password字段,數據類型varchar(30)
    password = models.CharField(max_length=30)
    # 對應數據表中email字段,數據類型varchar(254)
    email = models.EmailField()
    # 對應數據表中age字段,數據類型int()
    age = models.IntegerField()

數據庫的同步

在models.py中編寫好實體類後,須要同步到數據庫中

1.在控制檯終端進入項目主目錄,執行:

  ./manage.py  makemigrations

  做用:將每一個應用下的models.pu文件生成一個數據庫中間文件,保存在migrations目錄

2.繼續執行:

  ./manage.py  migrate

  做用:將每一個應用下的migrations目錄中的中間文件同步到數據庫中

 

模型的字段類型與字段選項

經常使用的字段類型:

  BooleanField()    -->布爾類型,實際就是數據庫中的tinyint(1)類型

  CharField()       --> 字符串類型

  DataField()       --> 日期類型

  DataTimeField()    --> 日期時間類型

  EmailField()     --> 存放電子郵箱

  FloatField()      --> 浮點型

  ImageField()       --> 存放圖片路徑

  IntergerField()    --> int整數型

  更多的字段類型,參考文檔:https://docs.djangoproject.com/en/2.0/ref/models/fields

 

經常使用字段選項:

  max_length    --> 指定最大長度,CharField()必須設置

  default      --> 設置當前字段的默認值

  null        --> 指定當前字段是否容許爲空,默認是False

  更多的字段選項,參考文檔:https://docs.djangoproject.com/en/2.0/ref/models/fields

 

模型中的增刪改查

一、增長數據,三種方式:

 

# 增長數據
def add_views(request):
    # 方式一:
    # 向author表中新增數據,Author是一個實體類(導入models.py)
    # Author.objects.create(names='朱自清', age=80)
    Author.objects.create(names='土豆', age=37,email='tudou@163.com')
    Author.objects.create(names='淨無痕', age=35, email='jing@163.com')
    Author.objects.create(names='耳根', age=40, email='ergeng@163.com')
    Author.objects.create(names='西紅柿', age=50, email='ergeng@163.com')
    Author.objects.create(names='唐家三少', age=46, email='ergeng@163.com')
    Author.objects.create(names='燜面', age=57, email='ergeng@163.com')

    # 方式二:
    # 建立一個Models對象,經過對象的save()完成增長
    obj = Author(names='老舍', age=65)
    obj.save()

    # 使用字典構造對象, 經過save()完成增長
    dic = {
        'names': '李白',
        'age': 35
    }
    obj = Author(**dic)
    obj.save()

    return HttpResponse('新增成功!')

 

二、修改數據:

# 修改數據
def update_views(request):
    # 修改單個數據(三步)
    # 1.經過get()獲得要修改的實體對象
    # 2.經過實體對象的屬性修改屬性值
    # 3.再經過實體對象的save()保存回數據庫
    au = Author.objects.get(id=1)
    au.names = '一葉知秋'
    au.save()

    # 批量修改數據(慎用)
    # 調用查詢結果集的update()完成批量修改
    Author.objects.all().update(age=18)

    return HttpResponse('修改爲功!')

 

三、刪除數據:

# 刪除數據
def delete_views(request, user_id):
  # 調用實體對象/查詢結果集的 delete()
  # 刪除單個
  # obj = Author.objects.get(id=1)
  # obj.delete()
  # 刪除多個
  # Author.objects.all().delete()

  # obj = Author.objects.get(id=user_id)
  # obj.delete()

  # 邏輯刪除
  au = Author.objects.get(id=user_id)
  au.isActive = False
  au.save()

  # 轉發(一次請求)
  # return aulist_views(request)

  # 重定向(從新向指定的url發送請求)
  return HttpResponseRedirect('/login/')

 

四、查看數據:

# 查詢數據
def query_views(request):
  # 方式一(查詢全部):
  # 查詢表中全部數據,至關於select * from 表名;
  auList = Author.objects.all()
  print(auList)
  # 返回的數據,是一個對象的列表,能夠迭代出對象遍歷出值
  # < QuerySet[ < Author: Author object >, < Author: Author object >, < Author: Author object >] >
  for au in auList:
    print('做者姓名:', au.names)
    print('做者年齡:', au.age)

  # 方式二(查詢指定字段):
  # 查詢表中部分字段數據,等同於select names,age from 表名;
  auList = Author.objects.values('names', 'age')
  print(auList)
  # 返回的數據是查詢的字段(字典,字段名:值)組成的列表
  for au in auList:
    print('做者姓名:', au['names'], '做者年齡:', au['age'])

  #############################################

  # 數據排序(默認是升序)
  # 按照age字段進行排序
  auList = Author.objects.order_by('age')
  print('#######升序#####')
  for au in auList:
    print(au.id, au.names, au.age)
  # Author.objects.order_by('-id')
  # 按照age字段進行降序排序
  auList = Author.objects.all().order_by('-age')
  print('######降序#######')
  for au in auList:
       print(au.id, au.names, au.age)


  #############################################
  # 對條件取反,等同於select * from 表名 where not (id=3)
  print('######條件取反######')
  auList = Author.objects.exclude(id=3)
  for au in auList:
       print(au.id, au.names, au.age)

  # 等同於 select * from author where not (id=3 and age=80)
  Author.objects.exclude(id=3, age=80)

  ##############################################
  # 根據條件查詢部分行(重難點)
  # 等同於select * from author where id=1
  Author.objects.filter(id=1)
  # 等同於select * from author where id=1 and names='老舍'
  Author.objects.filter(id=1, names='老舍')

  # 經過Field Lookup(查詢表達式)完成複雜條件的構建
  # __exact 表示精確查詢
  Author.objects.filter(names__exact='朱自清')

  # __contains 篩選出屬性中包含關鍵字的記錄
  # 等同於 select * from author where names like '%三少'
  auList = Author.objects.filter(names__contains='三少')
  print(auList[0].names)

  # __lt 和 __lte 分別表示篩選出屬性值小於和小於等於指定值得記錄
  # __gt 和 __gte 分別表示篩選出屬性值大於和大於等於指定值得記錄
  # 等同於 select * from author where age < 80
  Author.objects.filter(age__lt=80)
  # __startswith 篩選出以指定關鍵字開始的記錄
  # 等同於 select * from names like '朱%'
  Author.objects.filter(names__startswith='')
  # __endswith 篩選出以指定關鍵字結尾的記錄
  # 等同於 select * from names like '%三少'
  auList = Author.objects.filter(names__endswith='三少').values('names', 'age')
  for au in auList:
    print('做家姓名:', au['names'])
    print('做家年齡:', au['age'])

  ##############################################
  # 查詢只返回一條數據(該函數只適用於返回一條記錄時使用)
  Author.objects.get(id=1)

  return HttpResponse('查詢成功!')

 

下面還有幾個特殊操做:

一、F操做 和 Q操做

from django.db.models import F, Q


def doF_views(request):
  # 修改全部人的年齡所有加10歲
  # F操做, 在執行操做時獲取某列的值(脫離操做無效)
  Author.objects.all().update(age=F('age')+10)
  return HttpResponseRedirect('/index/')


def doQ_views(request):
  # Q操做, 在查詢條件中實現或(or)的功能
  # 等用於 select * from author where (id=8 or age>=50) and isActive=True;
  auList = Author.objects.filter(Q(id=8) | Q(age__gte=50), isActive=True)
  return render(request, 'index.html', locals())

 

二、原生數據庫操做:

def raw_views(request):
  sql = 'select * from index_author where id>=9'
  auList = Author.objects.raw(sql)

  for au in auList:
    print(au.names, au.age)
  return HttpResponse('Execute raw success!')

 

ps: 這裏補充一點內容,重定向:

  意思就是想新的地址發送請求(服務器端)

  from django.http import HttpResponseRedirect

  return HttpResponseRedirect(url)

 

未完待續....

相關文章
相關標籤/搜索