django框架使用-生成數據庫表

前言

本篇簡單介紹django中對數據庫的操作.

create數據庫表

上一篇中使用python manage.py runserver 8000運行django項目, 雖然項目成功運行, 但發現終端中有一些警告信息.
這些警告信息表示此項目有數據庫結構的設計但是沒有應用到數據庫中.
下面先介紹兩個命令.

python manage.py makemigrations
python manage.py migrate

控制臺中分別執行這兩行命令
控制臺輸出如下

bogon:HelloWorld zhaodan$ ls
HelloWorld      db.sqlite3      manage.py       mytest
bogon:HelloWorld zhaodan$ python manage.py makemigrations
No changes detected
bogon:HelloWorld zhaodan$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, sessions, contenttypes
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying sessions.0001_initial... OK
bogon:HelloWorld zhaodan$ open .

打開sqlite數據庫文件所在目錄

sqlitedir.png

與iOS開發中一模一樣的sqlite數據庫文件..., 使用工具打開數據庫文件.我使用的工具叫做 SQLite Professional,

sqlite0.png

能夠看到已經有了很多表.

我們一行代碼都沒有寫, 這些這些表是從哪里來的?

上面的兩行命令

python manage.py makemigrations
python manage.py migrate

是用來根據數據庫定義的代碼生成數據庫定義語句并執行的.
python manage.py makemigrations 會檢查數據庫定義的代碼是否正確.

django為我們提供了一套用戶系統. 包含user, usergroup, permissions等常用部分.

這些表的代碼來自這里.

auth0.png
auth1.png

仿照auth.models文件的內容 創建一個新表

user0.png

修改settings.py 文件
INSTALLED_APPS中添加mytest模塊

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

運行

python manage.py makemigrations
python manage.py migrate

最終效果

user1.png

以后會介紹具體如何編寫models.py文件中的各個表, 編寫時有哪些注意事項, models.py 文件被映射到數據庫后, 還能修改已經被映射過的字段嗎?

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容