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

Viewed 20770

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

5 Answers

@Daniel Naab's answer, as well as the doc in the official site, is not for executing management commands as an entrypoint.

When you want to use a management command as the entrypoint in managed cloud environment like AWS Lambda or Google Cloud Functions, you can take a look at manage.py and try something similar.

import os
from django.core.management import execute_from_command_line

def publishing_fn(data, context):
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YOURAPP.settings')
    # The first argument is "manage.py" when it's run from CLI.
    # It can be an empty string in this case
    execute_from_command_line(['', 'COMMAND', 'ARGS...'])
Related