面對現有的數據庫,Django如何寫models.py文件?

問題闡述

以往Django開發都是先寫models.py,然後完成命令“python manage.py magemigrations && python manage.py migrate”完成數據庫的建立。

現在,正好相反:已有現存的數據庫,這個models.py怎麼寫?

問題解決

關鍵命令: python manage.py inspectdb

首先,可以這樣看看 inspectdb 的操作解釋:

$ python manage.py  inspectdb --help

usage: manage.py inspectdb [-h] [--version] [-v {0,1,2,3}]
                           [--settings SETTINGS] [--pythonpath PYTHONPATH]
                           [--traceback] [--no-color] [--database DATABASE]
                           [table [table ...]]

Introspects the database tables in the given database and outputs a Django
model module.

positional arguments:
  table                 Selects what tables or views should be introspected.

optional arguments:
  -h, --help            show this help message and exit
  --version             show program's version number and exit
  -v {0,1,2,3}, --verbosity {0,1,2,3}
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, the
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Raise on CommandError exceptions
  --no-color            Don't colorize the command output.
  --database DATABASE   Nominates a database to introspect. Defaults to using
                        the "default" database.

然後,可以實際操作。
第一,項目的settings.py文件很重要。裏面記錄了關於數據庫的配置,如果沒有修改,那就默認是sqlite(如果原有數據庫就是slqite的話,直接可以將sqlite數據庫文件複製到manage.py 統計目錄下)。 如果settings.py文件修改爲其他數據的話,它會按照配置去讀取數據庫原有記錄。

第二,開始執行生成models.py文件。

# 如果已經執行過 python manage.py startapp 命令生成應用,直接覆寫
python manage.py  inspectdb > app/models.py 

# 如果沒有執行過 python manage.py startapp 命令生成應用,可以直接將生成的models內容輸出爲 models.py文件
python manage.py  inspectdb > models.py 

# 其實這兩步區別不大,就是一個方便性的問題。

有了models.py 文件,省去了不少手寫的功夫,倒也是快捷方便。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章