Django(5)-model

環境準備

  • 建立一個新項目
django-admin startproject djangomodel
django-admin startapp App
python manage.py startapp App
  • 建立templates並標記
  • settings.py
ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'App',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR,'templates')
        ],
        

DATABASES = {
    'default': {
        # 'ENGINE': 'django.db.backends.sqlite3',
        # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'GP1djangomodel',
        'PORT':'3306',
        'HOST':'localhost',
        'USER':'root',
        'PASSWORD':'mysql',

    }
}


LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
  • __init__.py
import pymysql
pymysql.install_as_MySQLdb()
  • mysql建立庫
mysql> create database GP1djangomodel charset=utf8;
Query OK, 1 row affected (0.17 sec)
  • 遷移數據庫
python manage.py startapp App

今日內容

model

  • 在企業開發中,咱們一般是從數據開始開發的python

    開發流程

  1. 配置數據庫
  2. 定義模型類(一個模型類對應數據庫中的一張表)
  3. 生成遷移文件
  4. 執行遷移生成數據表
  5. 使用模型類進行增刪改查(CRUD)操做mysql

    ORM

    ORM(object relational mapping)對象關係映射,是一種程序技術,用於實現面向對象編程語言裏不一樣類型系統的數據之間(數據與數據庫之間)的轉換,能夠簡單理解爲翻譯機,核心思想是解耦,將業務邏輯與數據庫的SQL語句進行解耦sql

graph LR
實體-->ORM
ORM-->數據庫
graph LR
model-->ORM
ORM-->database
  • 對象關係映射
  • 理解爲翻譯機
  • 核心思想,解耦合
    • 將業務邏輯和SQL進行了解耦數據庫

      Django定義模型

  • 重要概念:表,屬性,字段
  • 一個模型在數據庫中對應一張表,在模型類中定義的屬性,對應該模型對照表中的一個字段
  • 定義屬性見定義屬性文件
  • 建立模型類
  • 元選項,在模型中定義Meta,用於設置元信息(類中類)
class Meta:
        db_table=xxx #定義數據表名,推薦使用小寫字母
        ordering = []
        #對象的默認排序字段,獲取對象列表時使用,一般是integer類型,升序ordering['id'],降序ordering['-id']

數據庫中數據類型

  • 字符串
  • 數字
  • 日期時間
  • models.py
from django.db import models

# Create your models here.
#假裝Django模型
class Person(models.Model):
    # 約束,用戶名不容許重複
    p_name = models.CharField(max_length=16,unique=True)
    # 默認18歲
    p_age = models.IntegerField(default=18,db_column='age')
    # False 表明男,True表明女,db_column映射
    p_sex = models.BooleanField(default=False,db_column='sex')
    #改表名
    class Meta:
        db_table = 'People'
E:\py27\Django_project\djangomodel>python manage.py makemigrations
Migrations for 'App':
  App\migrations\0001_initial.py
    - Create model Person

E:\py27\Django_project\djangomodel>python manage.py migrate
Operations to perform:
  Apply all migrations: App, admin, auth, contenttypes, sessions
Running migrations:
  Applying App.0001_initial... OK

模型成員objects

Django默認經過模型的objects對象實現模型數據查詢
Django有兩種過濾器用於篩選記錄django

  • filter : 返回符合篩選條件的數據集
  • exclude : 返回不符合篩選條件的數據集

多個filter和exclude能夠鏈接在一塊兒查詢編程

模型過濾
    * filter
    * exclude
    * 連續使用
        * 鏈式調用
        * Persion.objects.filter(條件).filter(條件).xxx.exclude().exclude()

建立model

  • djangomodel/urls.py
from django.contrib import admin
from django.conf.urls import url,include

urlpatterns = [
    url('admin/', admin.site.urls),
    url('^App/',include('App.urls')),
]

添加用戶session

  • App/urls.py
#conding:utf-8
from django.conf.urls import url
from App import views
urlpatterns = [
    url(r'^addpersions/',views.add_persions),

]
  • App/views.py
from django.shortcuts import render,HttpResponse
from App.models import Person
import random
# Create your views here.
def add_persions(request):
    for i in range(15):
        persion = Person()
        flag = random.randrange(100)
        persion.p_name = 'Tom%d' %i
        persion.p_age = flag
        persion.p_sex = flag%2
        persion.save()
    return HttpResponse("批量建立成功")

查詢用戶app

#conding:utf-8
from django.conf.urls import url
from App import views
urlpatterns = [
    url(r'^addpersions/',views.add_persions),
    url(r'getpersions/',views.get_persions),

]
  • 過濾條件1 filter(將知足條件的拿出來)
def get_persions(request):
    persion = Person.objects.filter(p_age__gt=18)
    context = {
        "persion":persion
    }
    return render(request,'persion_list.html',context=context)
  • 過濾條件2
def get_persions(request):
    persion = Person.objects.filter(p_age__gt=50)
    context = {
        "persion":persion
    }
    return render(request,'persion_list.html',context=context)
  • 過濾條件3(級聯調用)
def get_persions(request):
    persion = Person.objects.filter(p_age__gt=50).filter(p_age__lt = 80)
    context = {
        "persion":persion
    }
    return render(request,'persion_list.html',context=context)
  • 過濾條件4 exclude(將知足條件的踢走)
def get_persions(request):
    # persion = Person.objects.filter(p_age__gt=50).filter(p_age__lt = 80)
    persion = Person.objects.exclude(p_age__lt=50)
    context = {
        "persion":persion
    }
    return render(request,'persion_list.html',context=context)
  • 過濾條件5
def get_persions(request):
    # persion = Person.objects.filter(p_age__gt=50).filter(p_age__lt = 80)
    persion = Person.objects.exclude(p_age__lt=50).filter(p_age__lt=80)
    context = {
        "persion":persion
    }
    return render(request,'persion_list.html',context=context)
  • persion類型,是查詢結果集
def get_persions(request):
    # persion = Person.objects.filter(p_age__gt=50).filter(p_age__lt = 80)
    persion = Person.objects.exclude(p_age__lt=50).filter(p_age__lt=80)
    print(type(persion))
    context = {
        "persion":persion
    }
    return render(request,'persion_list.html',context=context)
    
System check identified no issues (0 silenced).
November 28, 2019 - 11:37:41
Django version 1.11.26, using settings 'djangomodel.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
<class 'django.db.models.query.QuerySet'> #不是列表,可是可迭代
[28/Nov/2019 11:37:41] "GET /App/getpersions/ HTTP/1.1" 200 478
<class 'django.db.models.query.QuerySet'>
[28/Nov/2019 11:37:43] "GET /App/getpersions/ HTTP/1.1" 200 478
  • 過濾條件 6
def get_persions(request):
    # persion = Person.objects.filter(p_age__gt=50).filter(p_age__lt = 80)
    persion  = Person.objects.exclude(p_age__lt=50).filter(p_age__gt=80)
    print(type(persion))
    persiontwo = Person.objects.filter(p_age__in=[40,30,47])
    print(type(persiontwo))
    context = {
        "persion":persion,
        "persiontwo":persiontwo
    }
    return render(request,'persion_list.html',context=context)
  • templates/persion_list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>persion_list</title>
</head>
<body>
<h3>PersionList</h3>
<ul>
    {% for persion in persion %}
    <li>姓名:{{ persion.p_name }} 年齡:{{ persion.p_age }}</li>
    {% endfor %}
</ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>persion_list</title>
</head>
<body>
<h3>PersionList</h3>
<ul>
    {% for persion in persion %}
    <li>姓名:{{ persion.p_name }} 年齡:{{ persion.p_age }}</li>
    {% endfor %}
</ul>
<ul>
    {% for persiontwo in persiontwo %}
       <li>姓名2:{{ persiontwo.p_name }} 年齡2:{{ persiontwo.p_age }}</li>
    {% endfor %}
</ul>
</body>
</html>

建立對象

目的:向數據庫中添加數據dom

當建立對象時,Django不會對數據庫進行讀寫操做,當調用save()方法時才與數據庫交互,將對象保存到數據庫中

注意:__init__已經在父類models.Model中使用,在自定義的模型中沒法使用

建立對象方案:

在模型類中增長類方法去建立對象

@classmethod

def create(cls,name,age):

在自定義的管理器中添加方法來建立對象
#conding:utf-8
from django.conf.urls import url
from App import views
urlpatterns = [
    url(r'^addpersions/',views.add_persions),
    url(r'getpersions/',views.get_persions),
    url(r'^addperson',views.add_person),

]
  • 要求寫的字段都必須寫
def add_person(request):
    person = Person.objects.create(p_name = '小明',p_age = 15,p_sex=True)
    person.save()
    return HttpResponse('小明建立成功')

方法

  • 對象方法
    • 能夠調用對象的屬性,也能夠調用類的屬性
  • 類方法
    • 不能調用對象屬性,只能調用類屬性
  • 靜態方法
    • 啥都不能調用,不能獲取對象屬性,也不能獲取類熟悉
    • 只是寄生在咱們這個類上而已
from django.db import models

# Create your models here.
#假裝Django模型
class Person(models.Model):
    # 約束,用戶名不容許重複
    p_name = models.CharField(max_length=16,unique=True)
    # 默認18歲
    p_age = models.IntegerField(default=18,db_column='age')
    # False 表明男,True表明女,db_column映射
    p_sex = models.BooleanField(default=False,db_column='sex')
    p_hobby = models.CharField(max_length=32,null=True,blank=True)
    #改表名
    @classmethod
    def create(cls,p_name,p_age=100,p_sex=True,p_hobby='gaming'):
        return cls(p_name=p_name,p_age=p_age,p_hobby=p_hobby)
    class Meta:
        db_table = 'People'
def add_person(request):
    # person = Person.objects.create(p_name = '小明',p_age = 15,p_sex=True)
    # person.save()
    # person = Person(p_age=28)
    # 是"" None Null 不能重寫__init__ 能夠經過其餘手段,實現屬性自定義賦值
    person = Person.create('jack')
    person.save()
    return HttpResponse('建立成功')
相關文章
相關標籤/搜索