3

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'
3

4 Answers 4

2

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/

Sign up to request clarification or add additional context in comments.

3 Comments

The long-term goal for this script is reporting. Basically, I will end up using jenkins to run this script once-per week, so I am unsure if this will work for my particular use case.
I don't see why this doesn't work for your use case. Can't Jenkins run python manage.py <your script name> just as easily as it runs python <your script name>?
You're right, this worked flawlessly. Thank you very much for the assistance!
1

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

Comments

1

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.