在django中,如何从初始化脚本调用子命令“syncdb”? [英] In django, how do I call the subcommand 'syncdb' from the initialization script?

查看:197
本文介绍了在django中,如何从初始化脚本调用子命令“syncdb”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python和django的新手,并且遵循 Django Book 我学到了为我生成数据库表的命令python manage.py syncdb。在开发环境中,我在内存数据库中使用sqlite,所以每次重新启动服务器时都会自动删除它。那么如何编写这个'syncdb'命令呢?(应该在'settings.py'文件里面)?



CLARIFICATION / p>

OP正在使用内存数据库,需要在使用针对该数据库定义的Django模型的任何进程的开始时初始化内存。什么是确保数据库初始化的最佳方法(每个进程一次启动)。这将是通过 manage.py runserver 或通过Web服务器进程(例如使用WSGI或mod_python)运行测试或运行服务器。

解决方案

所有Django管理命令的运行管理命令

  from django.core.management import call_command 
call_command('syncdb',interactive = True)

理想情况下,您将使用 runserver 之前的初始化信号来激活此信号,但这样的信号不存在。所以,实际上,如果我是这样,我将会处理这个方法,就是创建一个自定义的管理命令,比如 runserver_newdb ,然后在其中执行:

 从django.core.management import call_command 
call_command('syncdb',interactive = True)
call_command('runserver ')

请参阅文档,了解有关编写自定义管理命令的更多信息。


I'm new to python and django, and when following the Django Book I learned about the command 'python manage.py syncdb' which generated database tables for me. In development environment I use sqlite in memory database, so it is automatically erased everytime I restart the server. So how do I script this 'syncdb' command?(Should that be done inside the 'settings.py' file?)

CLARIFICATION

The OP is using an in-memory database, which needs to be initialized at the start of any process working with Django models defined against that database. What is the best way to ensure that the database is initialized (once per process start). This would be for running tests, or running a server, either via manage.py runserver or via a webserver process (such as with WSGI or mod_python).

解决方案

All Django management commands can be accessed programmatically:

from django.core.management import call_command
call_command('syncdb', interactive=True)

Ideally you'd use a pre-init signal on runserver to activate this, but such a signal doesn't exist. So, actually, the way I'd handle this if I were you would be to create a custom management command, like runserver_newdb, and execute this inside it:

from django.core.management import call_command
call_command('syncdb', interactive=True)
call_command('runserver')

See the documentation for more information on writing custom management commands.

这篇关于在django中,如何从初始化脚本调用子命令“syncdb”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆