Django Standalone Script

后端 未结 4 1455
死守一世寂寞
死守一世寂寞 2020-12-01 07:43

I am trying to access my Django (v1.10) app DB from another python script and having some trouble doing so.

This is my file and folder structure:

sto         


        
相关标签:
4条回答
  • 2020-12-01 08:13

    Try this

    import sys, os, django
    sys.path.append("/path/to/store") #here store is root folder(means parent).
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "store.settings")
    django.setup()
    
    from store_app.models import MyModel
    

    This script you can use anywhere in your system.

    0 讨论(0)
  • 2020-12-01 08:22

    This sounds like a great use case for Django Management commands. which has the added bonus you can run it scheduled from cron, direct from the commandline, or call from inside django. This gives the script full access to the same settings and environment variables as your main project.

    If you move this into an appropriate directory - using store here as an example, not a suggestion, it should work.

    store 
        management 
        __init__.py
            commands
            __init__.py 
            otherscript.py 
    
    0 讨论(0)
  • 2020-12-01 08:23

    I found the django-extensions package to be most useful. You can find it here

    After installation and adding it to the installed apps, all you need to do is to create a directory called scripts, create a file and run it by python manage.py runscript file_name

    Just remember that the file must have an entry point. That entry point is a method called run which has to be present and will run once you run python manage.py runscript file_name in the terminal

    0 讨论(0)
  • 2020-12-01 08:23

    try to import from store_app.models - as the surrounding store folder is not a python module and should not be used when importing.

    import django
    from django.conf import settings
    
    settings.configure(DEBUG=True)
    django.setup()
    
    from store_app.models import MyModel
    

    update: i just noticed that you put that script next to your project folder - you should move it inside for this to work.

    0 讨论(0)
提交回复
热议问题