[PYTHON] Use Django features from batch scripts outside your Django project

When you want to do batch processing in Django, you write management commands.

However, there are occasional batch processes that are not enough to write management commands. A data migration script that is written down. A counting tool just for troubleshooting.

In that case, you can access Django features from a Python file outside your Django project without having to register it as a management command.

Have a script like this ready.

django_setup.py


"""
django_setup()When you run Django's features(Model import etc.)Will be available.
"""

import os
import sys
import django


def django_setup():
    os.environ.setdefault(
        'DJANGO_SETTINGS_MODULE', 'myapp.settings')
    base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
    sys.path.append(os.path.join(base_dir, 'myproject'))
    django.setup()

All you have to do is add the Django project root (where ./manage.py is) to sys.path and run django.setup ().

If you're using your own configuration file, specify it in the environment variable DJANGO_SETTINGS_MODULE.

I follow __file__ with ʻos.path.dirname`, but please change this according to your environment. Assuming base_dir is the "up one" directory of your Django project (myproject).

If you do this, you can write a script etc.

from django_setup import django_setup


def main():
    from myapp.models import MyModel
    
    for item in MyModel.objects.filter(...):
        ...

  
if __name__ == '__main__':
  django_setup()
  main()

In this way, you can access features within your Django project.

Recommended Posts

Use Django features from batch scripts outside your Django project
Use django model from interpreter
Register your Django application in your project
Use BigQuery from your local Jupyter Notebook
Use Django from a local Python script
[Python] Introduce UIKit3 to your Django project
Use Python in your environment from Win Automation