luistm
luistm

Reputation: 1027

How to use Django in a Python script?

Is it possible to use Django in a python script?

I think I saw something about it in the past, but I can't find any reference to it now. So, basically, I want to build a python script and access Django ORM.

Thanks for any help

Upvotes: 0

Views: 446

Answers (2)

John Gordon
John Gordon

Reputation: 33335

import sys
import os
sys.path.insert(0, 'root directory of my project')
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
import django
django.setup()
from myapp.models import MyModel

# now you can access MyModel objects just as if you were in a django view

Upvotes: 2

cetver
cetver

Reputation: 11829

TLDR:

if __name__ == '__main__':
    import django
    django.setup()

More info

Upvotes: 1

Related Questions