Django 常用指令


建立時間: 2022年9月1日 07:35
更新時間: 2023年8月14日 02:10

說明

這次來分享 Django 很常用的指令
算是一種懶人包的概念
這篇之後會陸續更新,若沒提到的部分可到參考查看相關資料

指令

$ python manage.py collectstatic

把靜態目錄下的所有文件拷貝至 STATIC_ROOT 目錄
這是 Django 管理靜態文件的指令,這是很常見的功能
你可以到 How to manage static files (e.g. images, JavaScript, CSS) 了解更多


$ python manage.py makemigrations

根據檢測到的模型變化創建新的遷移。
當你更新 model 時就會下這個指令
接著再同步 $ python manage.py migrate


$ python manage.py migrate

將數據庫狀態與當前的模型集和遷移同步


$ python manage.py runserver

在本地機器上啟動一個輕量級的開發網絡服務器。
非常方便地建立一個本地環境。

參數

  • –settings=config.settings.local
    • 指定設定檔 setting.py 路徑,有時候開發不同環境會使用不同設定檔,後面 config.settings.local 是範例,請修改成你的設定檔路徑

$ python manage.py shell

啟動 Python 交互式直譯器,就好像在終端執行 $ python 進入 python 直譯器一樣,我看大部分的範例都是用這個直譯器直接執行資料庫操作。

以下是 Django 範例片段內容

>>> from polls.models import Choice, Question  # Import the model classes we just wrote.

# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>

# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())

# Save the object into the database. You have to call save() explicitly.
>>> q.save()

# Now it has an ID.
>>> q.id
1

$ python manage.py startapp app_name

創建一個應用程式,你可以把 Django 當作一個專案,裡面可以有多個應用程式。

參考

觀看次數: 1528
djangomanagermigraterunservershellstartapp
按讚追蹤 Enjoy 軟體 Facebook 粉絲專頁
每週分享資訊技術

一杯咖啡的力量,勝過千言萬語的感謝。

支持我一杯咖啡,讓我繼續創作優質內容,與您分享更多知識與樂趣!