Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In django, how do I call the subcommand 'syncdb' from the initialization script?

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).

like image 978
Thiago Padilha Avatar asked Aug 16 '10 18:08

Thiago Padilha


People also ask

What is Syncdb command in Django?

syncdb is a command which is executed in django shell to create tables for first time for apps which are added to INSTALLED_APPS of settings.py. Need to keep in mind about two key words: 'First Time' and 'Newly Added Apps'.

What is the name of the command line tool that Django?

django-admin is Django's command-line utility for administrative tasks. This document outlines all it can do. In addition, manage.py is automatically created in each Django project.


1 Answers

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.

like image 144
Daniel Naab Avatar answered Oct 11 '22 14:10

Daniel Naab