use this solution only if you want your scripts to be standalone (you want to access models when server is not running)
There are basically two different ways to do that:
If you are going to run this code frequently, I strongly suggest that you create a management command for the code. (check instructions here)
But if it's a bulk-data-import or something that's not gonna run many times, you can use something like this (put this in the root of your django app - beside manage.py):
import os
import django
if __name__ == '__main__':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<your_project_name>.settings")
django.setup()
# now you have access to your models
# as an example:
# from users.models import User
#
# for user in User.objects.all():
# print(user)
also keep in mind that you should always import your models after django.setup()
, otherwise, you'll get an error.
I would also appreciate it if someone could advise me whether or not it is accurate to place an init.py module within the root directory. If not, what is the best way of doing this?
If you want to have multiple script files, it's not a good idea to put them in the root of django project. You can create a python package, say my_scripts
, beside manage.py
and put your scripts there.
So you will end up with something like this:
...
manage.py
my_scripts
├── __init__.py
└── first_script.py
But now you need to make a little change in the script file to make it work correctly. You should append the BASE_DIR
to your path so that python can recognize the settings
file (or module, if you extend it):
import os
import sys
import django
if __name__ == '__main__':
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<your_project_name>.settings")
django.setup()
# now you have access to your models
# as an example:
# from users.models import User
#
# for user in User.objects.all():
# print(user)