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

问题阐述
以往Django开发都是先写models.py,然后完成命令“python manage.py magemigrations && python manage.py migrate”完成数据库的建立。

现在,正好相反:已有现存的数据库,这个models.py怎么写?

问题解决
关键命令: python manage.py 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 文件,省去了不少手写的功夫,倒也是快捷方便。
转载:https://blog.csdn.net/Kohang/article/details/80296042

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值