溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Django數(shù)據(jù)庫SQlite如何使用

發(fā)布時間:2022-09-20 15:00:08 來源:億速云 閱讀:189 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Django數(shù)據(jù)庫SQlite如何使用”,在日常操作中,相信很多人在Django數(shù)據(jù)庫SQlite如何使用問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Django數(shù)據(jù)庫SQlite如何使用”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

1:創(chuàng)建工程

django-admin startproject mysite

創(chuàng)建完成后,工程目錄結(jié)構(gòu)如下:

Django數(shù)據(jù)庫SQlite如何使用

manage.py ----- Django項目里面的工具,通過它可以調(diào)用django shell和數(shù)據(jù)庫等。

settings.py ---- 包含了項目的默認(rèn)設(shè)置,包括數(shù)據(jù)庫信息,調(diào)試標(biāo)志以及其他一些工作的變量。

urls.py ----- 負(fù)責(zé)把URL模式映射到應(yīng)用程序。

2:創(chuàng)建blog應(yīng)用

python manage.py startapp blog

完成后,會在項目中生成一個blog的文件夾 

Django數(shù)據(jù)庫SQlite如何使用

3:數(shù)據(jù)庫操作 

初始化數(shù)據(jù)庫:

python 自帶SQLite數(shù)據(jù)庫,Django支持各種主流的數(shù)據(jù)庫,這里我們首先使用SQLite。

如果使用其它數(shù)據(jù)庫請在settings.py文件中設(shè)置。數(shù)據(jù)庫默認(rèn)的配置為:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

 使用默認(rèn)的數(shù)據(jù)配置來初始化數(shù)據(jù)庫:

命令執(zhí)行完成后,會生成一些數(shù)據(jù)表:

Django數(shù)據(jù)庫SQlite如何使用

 Django自帶有一個WEB 后臺,下面創(chuàng)建WEB后臺的用戶名與密碼:

python manage.py createsuperuser

注意??:密碼不能與用戶名相似,密碼不能純數(shù)字 。

Django數(shù)據(jù)庫SQlite如何使用

 接下來我們使用上面創(chuàng)建的賬號密碼登錄后臺試試。要登錄后臺,必須在settings.py文件中將上面創(chuàng)建的APP也就是blog添加進來:

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

注意后面必須要有個逗號!

啟動django容器:

python manage.py runserver

默認(rèn)使用的WEB地址為http://127.0.0.1,端口為8000,使用該地址與端口訪問首頁:

Django數(shù)據(jù)庫SQlite如何使用

 下面訪問django的后臺:http://127.0.0.1/admin

Django數(shù)據(jù)庫SQlite如何使用

創(chuàng)建一張UseInfo表,并創(chuàng)建字段:

現(xiàn)在我們打開blog目錄下的models.py文件,這是我們定義blog數(shù)據(jù)結(jié)構(gòu)的地方。打開mysite/blog/models.py 文件進行修改:

from django.db import models
 
 
# Create your models here.
class Demo(models.Model):
    car_num = models.CharField(max_length=32)
    park_name = models.CharField(max_length=32)
    jinru_Date = models.CharField(max_length=32)
    chuqu_Date = models.CharField(max_length=32)
    time = models.CharField(max_length=32)

命令行執(zhí)行:

python manage.py makemigrations
python manage.py migrate

Django數(shù)據(jù)庫SQlite如何使用

從上圖中可以看出,Django默認(rèn)會以APP名為數(shù)據(jù)表前綴,以類名為數(shù)據(jù)表名!

創(chuàng)建的字段如下圖:

Django數(shù)據(jù)庫SQlite如何使用

4.在blog_demo表中添加數(shù)據(jù):

Django是在views.py文件中,通過導(dǎo)入models.py文件來創(chuàng)建數(shù)據(jù)的:

from django.shortcuts import render
 
# Create your views here.
 
from blog import models  # 導(dǎo)入blog模塊
from django.shortcuts import HttpResponse
 
def db_handle(request):
    # 添加數(shù)據(jù)
    models.Demo.objects.create(car_num='陜E-BV886', park_name='中醫(yī)院', jinru_Date='2022-02-05',
                                   chuqu_Date='2022-02-06', time='1')
    return HttpResponse('OK')

 下面我們配置路由,以便讓瀏覽器能夠訪問到views.py文件:

from blog import views
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'db_handle', views.db_handle),
]

 下面我們來訪問http://127.0.0.1/db_handle

Django數(shù)據(jù)庫SQlite如何使用

查看數(shù)據(jù)庫是否創(chuàng)建成功:

Django數(shù)據(jù)庫SQlite如何使用

 上面就是創(chuàng)建表數(shù)據(jù),也可以通過字典的格式來創(chuàng)建表數(shù)據(jù):

def db_handle(request):
    dic = {car_num='陜E-BV886', park_name='中醫(yī)院', jinru_Date='2022-02-05',chuqu_Date='2022-02-06', time='1'}
    models.Demo.objects.create(**dic)
    return HttpResponse('OK')

刪除表數(shù)據(jù):

views.py文件如下:

def db_handle(request):
 
    #刪除表數(shù)據(jù)
    models.Demo.objects.filter(id=1).delete()
    return HttpResponse('OK')

 操作方法同上,在瀏覽器中執(zhí)行一遍,數(shù)據(jù)中的id=1的數(shù)據(jù)即被刪除:

Django數(shù)據(jù)庫SQlite如何使用

修改表數(shù)據(jù): 

def db_handle(request):
    # 修改表數(shù)據(jù)
    models.Demo.objects.filter(id=2).update(time=18)  
    return HttpResponse('OK')

數(shù)據(jù)的查詢:

為了讓查詢出來的數(shù)據(jù)更加直觀地顯示出來,這里我們將使用Django的模板功能,讓查詢出來的數(shù)據(jù)在WEB瀏覽器中展示出來

在templates目錄下新建一個t1.html的文件,內(nèi)容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Django操作數(shù)據(jù)庫</title>
    <link type="text/css" href="/static/base.css" rel="external nofollow"  rel="external nofollow"  rel="stylesheet" />
</head>
<body>
    <table border="1">
        <tr>
            <th>車牌號</th>
            <th>停車場名</th>
            <th>入場時間</th>
            <th>出場時間</th>
            <th>停車時間</th>
        </tr>
        {% for item in li %}
        <tr>
            <td>{{ item.car_num }}</td>
            <td>{{ item.park_name }}</td>
            <td>{{ item.jinru_Date }}</td>
            <td>{{ item.chuqu_Date }}</td>
            <td>{{ item.time }}</td>
         </tr>
        {% endfor %}
</body>
</html>

views.py文件查詢數(shù)據(jù),并指定調(diào)用的模板文件,內(nèi)容如下:

def db_handle(request):
        user_list_obj = models.Demo.objects.all()
        return render(request, 't1.html', {'li': user_list_obj})

注意:由于這里是在工程下面的templates目錄下建立的模板,而不是在blog應(yīng)用中創(chuàng)建的模板,上面views.py文件中調(diào)用的t1.html模板,運行時會出現(xiàn)找不到t1.html模板的錯誤,為了能找到mysite/templates下的模板文件,我們還需要在settings.py文件配置模板的路徑:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],  # 配置模板路徑
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

下面就可以在瀏覽器中查看:

Django數(shù)據(jù)庫SQlite如何使用

引入JS,CSS等靜態(tài)文件:

在mysite目錄下新建一個static目錄,將JS,CSS文件都放在此目錄下!并在settings.py文件中指定static目錄:

Django數(shù)據(jù)庫SQlite如何使用

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

表單提交數(shù)據(jù):

在Django中要使用post方式提交表單,需要在settings.py配置文件中將下面一行的內(nèi)容給注釋掉:

# 'django.middleware.csrf.CsrfViewMiddleware',

提交表單(這里仍然使用了t1.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Django操作數(shù)據(jù)庫</title>
    <link type="text/css" href="/static/base.css" rel="external nofollow"  rel="external nofollow"  rel="stylesheet" />
</head>
<body>
    <table border="1">
        <tr>
            <th>車牌號</th>
            <th>停車場名</th>
            <th>入場時間</th>
            <th>出場時間</th>
            <th>停車時間</th>
        </tr>
        {% for item in li %}
        <tr>
            <td>{{ item.car_num }}</td>
            <td>{{ item.park_name }}</td>
            <td>{{ item.jinru_Date }}</td>
            <td>{{ item.chuqu_Date }}</td>
            <td>{{ item.time }}</td>
         </tr>
        {% endfor %}
    </table>
    <form action="/db_handle" method="post">
         <p><input name="car_num" /></p>
         <p><input name="park_name" /></p>
         <p><input name="jinru_Date" /></p>
         <p><input name="chuqu_Date" /></p>
         <p><input name="time" /></p>
         <p><input type="submit" value="submit" /></p>
     </form>
</body>
</html>

寫入數(shù)據(jù)庫(views.py):

def db_handle(request):
        if request.method == "POST":
                 models.Demo.objects.create(car_num=request.POST['car_num'],park_name=request.POST['park_name'],jinru_Date=request.POST['jinru_Date'],chuqu_Date=request.POST['chuqu_Date'],time=request.POST['time'])
        user_list_obj = models.Demo.objects.all()
        return render(request, 't1.html', {'li': user_list_obj})

提交數(shù)據(jù)后,如下圖:

Django數(shù)據(jù)庫SQlite如何使用

Django數(shù)據(jù)庫SQlite如何使用

Django數(shù)據(jù)庫SQlite如何使用

到此,關(guān)于“Django數(shù)據(jù)庫SQlite如何使用”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI