1. 程式人生 > 其它 >Django學習記錄3-連線資料庫

Django學習記錄3-連線資料庫

1.在專案目錄下settings.py配置連線的資料庫資訊

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'student',         # 你要儲存資料的庫名,事先要建立。
        'USER': 'root',         # 資料庫使用者名稱
        'PASSWORD': 'root',     # 密碼
        'HOST': 'localhost',    # 預設主機
        'PORT': '3306
', # 資料庫使用的埠 } }

2.在應用目錄下models.py 建立一個表資訊操作的Model表

from django.db import models

# Create your models here.
class Stu(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16)
    age = models.SmallIntegerField()
    sex = models.CharField(max_length=1)
    classid 
= models.CharField(max_length=8) def __str__(self) : return "%d:%s:%d:%s:%s"%(self.id, self.name, self.age, self.sex, self.classid) class Meta: db_table = "stu"

3.啟用模型

在專案目錄下settings.py新增應用程式

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    
'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "my_app" #新增應用 ]

4.呼叫

(1).進入互動式的Python shell

C:\Users\78461\Desktop\mysite>python manage.py shell
Python 3.9.4 (tags/v3.9.4:1f2e308, Apr  6 2021, 13:40:21) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from my_app.models import Stu
>>> mod = Stu.objects
>>> lists = mod.all()
>>> for u in lists:
...     print(u)
...
1:張三:18:male:python1
2:李四:17:male:python2
3:王五:18:female:python1
4:陸六:19:female:python2
>>> mod.get(id = 1)
<Stu: 1:張三:18:male:python1>

(2).在my_app應用的檢視中

在應用目錄下,views.py檔案

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
# Create your views here.

from django.http import HttpResponse
from my_app.models import Stu

def index(request):
    lists = Stu.objects.all()
    print(lists)
    print(Stu.objects.get(id = 1))
    return HttpResponse("ok")

在應用目錄下,新增路由地址

from django.urls import path
from . import views

urlpatterns = [
    path("",views.index, name="Student")
]

在專案目錄下,新增路由地址

from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from my_app import views


urlpatterns = [
    #path('admin/', admin.site.urls),
    url("stu/", include("my_app.urls"))
]

在專案目錄路徑下執行cmd

python manage.py runserver