[Django]-How to import all django models and more in a script?

5👍

After you run django.setup(), do this:

from django.apps import apps
for _class in apps.get_models():
    if _class.__name__.startswith("Historical"): 
        continue
    globals()[_class.__name__] = _class

That will make all models classes available as globals in your script.

0👍

Create a management command. It will automagically load django() and everything.
Then in your command you simply start your command. ./manage.py mytest

#myapp/management/commands/mytest.py
from django.core.management.base import BaseCommand, CommandError
from myapp.sometest import Mycommand

class Command(BaseCommand):
    help = 'my test script'

    def add_arguments(self, parser):
        pass
        # parser.add_argument('poll_ids', nargs='+', type=int)

    def handle(self, *args, **options):
        Mycommand.something(self)

which will call the actuall script:

#sometest.py
from .models import *
class Mycommand():
   def something(self):
       print('...something')
👤Alex

Leave a comment