面对现有的数据库,Django如何写models.py文件?

版权声明:本文为博主原创文章,未经博主允许不得转载。对于文中涉及到的参考文章,感谢作者分享,侵删。 https://blog.csdn.net/Kohang/article/details/80296042

问题阐述

以往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 文件,省去了不少手写的功夫,倒也是快捷方便。

猜你喜欢

转载自blog.csdn.net/Kohang/article/details/80296042