[Answered ]-How to properly import django project settings to interact with app's ORM?

1👍

it was solved by

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
    django.setup()

after that, i imported the ORMs and the models objects worked!

👤Ilja

1👍

Before running the program, please set PYTHONPATH variable to include your django project dir.

Suppose you have you django project in:
/home/anon/mydjangoproject

Then, before running your application, ensure you have:

export PYTHONPATH=$PYTHONPATH:/home/anon/mydjangoproject

These examples work in a Linux shell, please do a similar system environment variable setting for any other operating system.

0👍

I have faced the same problem while trying to build a background schedule cron job on Django 1.10.0

I fixed the issue by declaring the following on the top of the standalone script

import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE","myapp.settings")
django.setup()
#continue with the rest of your code

Hope this will fix the issue. It worked for me.

0👍

This is a project level connection

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

application = get_wsgi_application()

from app.model import ModelName
orm = ModelName.objects.all()
print(orm)

Next you can import models and execute django orm’s ,
It was tested in django 1.11.6

Thanks…..!

Leave a comment