Django學習筆記(2)-建立Model,連接資料庫

MVC架構中很重要的部分就是Model了,所以就練習一下在Django中怎麼建立Model
以及把新增資料、檢索資料、更新資料與刪除資料(CRUD)的簡易操作方法

先設定一下要連結的資料庫,在專案資料夾中的settings.py中

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'python_db',
        'USER': 'user',
        'PASSWORD': 'pass',
        'HOST':'localhost',
        'PORT':'3306',
    }
}

在Django中要使用Model比較麻煩一點,一定得建一個專用的ModelApp給他用
沒辦法像在Codeigniter上隨便愛怎麼叫就怎麼叫…所以先來建一下模型吧。
先回到manage.py所在的資料夾,下指令建立app

django-admin.py startapp Models

接著進去Models的APP裡編輯models.py,在裡面建立我們所需要的model類別
也就是要用到的Table,在這裡我只建一張只有name的名為Users的table,然後
django會自動幫忙加一個叫做id的主鍵

from django.db import models

# Create your models here.
class Users(models.Model):
    name = models.CharField(max_length=20)

然後再回到去編輯settings.py把剛剛建好的app給裝上

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Models', #加了這個
]

接著就使用Django的指令幫我們建立起table

$ python manage.py migrate
$ python manage.py makemigrations Models  #好像是讓Django去確認表格是否有變動
$ python manage.py migrate Models   #建立起模型

到這裡就完成DB的建立連結與MODEL的建立了!接下來回到專案裡的controllers中的index.py

先把MODEL跟http引進來

from Models.models import Users
from django.http import HttpResponse

新增資料(CREATE)的函數

def db_insert(request):
    #把GET或POST過來的資料轉為UTF8
    request.encoding='utf-8'
    #檢查GET參數裡面有沒有name的參數
    if 'name' in request.GET:
        #建立起 INSERT Models_users (name) VALUES ('xxxx') 的QUERY
        user_name = request.GET['name']
        new_record = Users(name=user_name)
        #執行QUERY
        new_record.save()
        response = user_name + ' was inserted into DB!'
    else:
        response = 'ERROR'

    return HttpResponse("<p>"response"</p>")

檢索所有資料(SELECT *)的函數

def db_select_all(request):
    response = ""
    #執行 SELECT * FROM Models_users
    list = Users.objects.all()

    #把每一列都印出來
    for user_info in list:
        response += str(user_info.id) + ':' + user_info.name + " "
    return HttpResponse("<p>" + response + "</p>")

用name來檢索資料(WHERE)的函數

def db_select_by_name(request):
    request.encoding='utf-8'
    response = ""
    if 'name' in request.GET:
        #把GET的值取出
        user_name = request.GET['name']
        #filter就是 WHERE
        list = Users.objects.all().filter(name=user_name)   
        for user_info in list:
            response += "<p>" + str(user_info.id) + ':' + user_info.name + "</p><br/>" 
    else:
        response = 'ERROR'

    return HttpResponse(response) 

更新資料(UPDATE)的函數

def db_update(request):
    request.encoding='utf-8'
    response = ""
    if 'id' in request.GET and 'name' in request.GET:
        user_id = request.GET['id']
        user_name = request.GET['name']
        #在Django中相當直覺,感覺上就好像是先把某個要更新的值取出然後在對他.update()的感覺:P
        Users.objects.filter(id=user_id).update(name=user_name)
        response = 'Updated!'
    else:
        response = 'ERROR'

    return HttpResponse(response) 

刪除資料(DELETE)的函數

def db_delete_by_id(request):
    request.encoding='utf-8'
    response = ""
    if 'id' in request.GET:
        user_id = request.GET['id']
        Users.objects.filter(id=user_id).delete()
        response = 'Deleted!'
    else:
        response = 'ERROR'

    return HttpResponse(response) 

函數都建立好之後就把Route給建立起來,所以編輯一下專案裡的urls.py

from django.contrib import admin
from django.urls import path
from .controllers import index

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', index.index),
    #從這邊下面是追加的URL
    path('db_insert', index.db_insert),
    path('db_select_all', index.db_select_all),
    path('db_select_by_name', index.db_select_by_name),
    path('db_update', index.db_update),
    path('db_delete_by_id', index.db_delete_by_id),
]

這樣就大功告成了~所以測試的時候用的URL如下

新增:http:localhost:8000/db_insert?name=xxxx

列出所有資料:http:localhost:8000/db_select_all

檢索name是xxxx的資料:http:localhost:8000/db_select_by_name?name=xxxx

把id是1的name更新為aaaa:http:localhost:8000/db_update?id=1&name=aaaa

刪除id是1的資料:http:localhost:8000/db_delete_by_id?id=1

搞定收工 :P

source: https://github.com/linmasahiro/django_connect_db