How to create Python script for Django app to access models without using manage.py shell?

To create Python script for Django app to access models without using , manage.py shell, we can import the model after calling os.environ.setdefault.

For instance, we write

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")

from your_project_name.models import Location

if __name__ == '__main__':    
    l = Location()
    l.name = 'Berlin'
    l.save()

    locations = Location.objects.all()
    print locations

    berlin = Location.objects.filter(name='Berlin')
    print berlin
    berlin.delete()

to add

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")

to set the environment to the Django environment.

Then we can import the Location model with

from your_project_name.models import Location

Then we can do what we want with the Location model in the if __name__ == '__main__' block.