[Fixed]-Use Django ORM outside of Django

19👍

So your question is :

I want to use Django’s ORM in my scripts without running a complete Django application, how to configure it?

I’ll share what I did for a project I am currently working on, using Django 2.0.2.

I suggest you create a file SetupDjangoORM.pywith :

import django
from django.conf import settings

settings.configure(
    DATABASES={
        'default': {
            'ENGINE': '<your_engine>',
            'NAME': '<database_name>',
            'HOST': '<hostname_or_ip>',
            'PORT': '<port>',
            'USER': '<user>',
            'PASSWORD': '<super_secret_password>',   
        }
    },
    INSTALLED_APPS=[
        '<your_app>',
    ]
)
django.setup()

You can find this informations in your settings.py file.

Then, you can import this wherever you need :

from . import SetupDjangoORM

And now you are able to use Django Models (ORM) in your scripts.

9👍

You can find all the information here

This works for version 3.1 of Django

import django
from django.conf import settings
from myapp import myapp_defaults

settings.configure(default_settings=myapp_defaults, DEBUG=True)
django.setup()

# Now this script or any imported module can use any part of Django it needs.
from myapp import models

5👍

Here’s an updated version, fix was including django.setup() line and some additional settings and includes:

manage.py

import os
import sys
import django
from django.conf import settings

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

INSTALLED_APPS = [
    'orm',
]

DATABASES = {
    'default': {
        'ENGINE' : 'django.db.backends.mysql',
        'NAME' : 'playground',
        'USER' : 'admin',
        'PASSWORD' : 'pasw',
        'HOST' : 'localhost',
    }
}

settings.configure(
    INSTALLED_APPS = INSTALLED_APPS,
    DATABASES = DATABASES,
)

django.setup()

if __name__ == "__main__":
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

And app.py:

import manage
from orm.models import Label

if __name__ == '__main__':

    Label.objects.create(name='test')
    print(Label.objects.get(name='test'))

Hope someone will find it useful.

👤NGix

Leave a comment