2

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'
Austin Hallett
  • 183
  • 1
  • 17
  • Does this answer your question? [Django script to access model objects without using manage.py shell](https://stackoverflow.com/questions/8047204/django-script-to-access-model-objects-without-using-manage-py-shell) – Sirwill98 Apr 20 '21 at 13:05
  • Unfortunately, I have attempted the solution in the above link, but I have not had any success. Still claims that there is no module named 'pages' – Austin Hallett Apr 20 '21 at 13:24

4 Answers4

1

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/

Brad Martsberger
  • 1,747
  • 13
  • 7
  • 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. – Austin Hallett Apr 20 '21 at 13:26
  • I don't see why this doesn't work for your use case. Can't Jenkins run `python manage.py ` just as easily as it runs `python `? – Brad Martsberger Apr 20 '21 at 14:20
  • You're right, this worked flawlessly. Thank you very much for the assistance! – Austin Hallett Apr 22 '21 at 18:34
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

John Kealy
  • 1,503
  • 1
  • 13
  • 32
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))
NKSM
  • 5,422
  • 4
  • 25
  • 38
-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