Austin Hallett
Austin Hallett

Reputation: 301

Import django models to custom python script

I am trying to create a custom python script within my Django application. This script requires the use of my app models. I am unable to figure out how to import the models appropriately to be used within this script.

My project directory:
-my_proj(name:ais)
-my_app(name:pages)
  -__init__.py
  -models.py
  -urls.py
   ...
  -utils
    -__init__.py
    -custom_script.py

So if I wanted to access the pages.models from the custom_script.py how might I do this?

I have attempted various imports such as from django.core.management import settings and from django.core.wsgi import get_wsgi_application but I still get an error stating the following:

ModuleNotFoundError: No module named 'pages'

Upvotes: 3

Views: 3082

Answers (4)

Thomas Beals
Thomas Beals

Reputation: 19

one way to see all of the models in your app is to import apps from django apps and use the get_models method.

from django.apps import apps

then you can use a comprehension in in order to view all of your models and their path. once you see the path you want you can import it at the top of your script.

models = { model.__name__: model for model in apps.get_models() }

input models into your shell to see the list of models in your app and the path from root

Also you make sure that you have import setup in your script

Upvotes: -1

NKSM
NKSM

Reputation: 5874

You can write a custom Command:

Add a management/commands directory to your app:

my_app/
    __init__.py
    models.py
    management/
        __init__.py
        commands/
            __init__.py
            my_command.py

Then you can create the file my_app/management/commands/my_command.py, contains something like below:

from django.core.management.base import BaseCommand, CommandError
from my_ap.models import MyModel

class Command(BaseCommand):
    help = 'Command to update some field'

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

    def handle(self, *args, **options):
        for cur_id in options['ids']:
            try:
                obj = MyModel.objects.get(pk=my_id)
            except MyModel.DoesNotExist:
                raise CommandError('MyModel "%s" does not exist' % my_id)

            obj.for_index = False
            obj.save()

            self.stdout.write(self.style.SUCCESS('Successfully closed "%s"' % my_id))

Upvotes: 1

John Kealy
John Kealy

Reputation: 1893

I always use runscript for this, which is part of django-extensions. It requires installing this library, but it's well worth it. You can then create a scripts/ directory in your project root, and you'll have all your models available.

Simply

pip install django-extensions

and then follow the steps here

Upvotes: 1

Brad Martsberger
Brad Martsberger

Reputation: 1967

There is a lot of app configuration done by Django to make your models and settings properly available. The best way to get Django to do this configuration is to make your script a management command, which will be run by python manage.py <your_script_name>. How to make your own management commands is covered by the docs. https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/

Upvotes: 2

Related Questions