Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Django ORM outside of Django

I'm new to Django and want to use its ORM in my scripts without running whole Django thing. I'm scratching my head how to configure it. Searches on StackOverflow didn't help as answers don't show the full picture.

Therefore, I created a small project:

app.py
manage.py
orm/
  __init__.py
  models.py

manage.py has configuration:

from django.conf import settings    
settings.configure(
    DATABASE_ENGINE = 'mysql',
    DATABASE_NAME = 'db',
    DATABASE_USER = 'admin',
    DATABASE_PASSWORD = '',
    DATABASE_HOST = 'localhost',    
    INSTALLED_APPS = ('orm')
)

models.py:

from django.db import models    
class Label(models.Model):
    name = models.CharField(max_length=50) # required max_length

and finally my main file app.py:

from django.conf import settings    
from django.db import models
from orm.models import *   
\# do database maniupaltions

Though after running app.py I receive an error that: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

What am I doing wrong?

like image 633
NGix Avatar asked Aug 09 '17 16:08

NGix


2 Answers

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
like image 100
avimimoun Avatar answered Sep 26 '22 21:09

avimimoun


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.

like image 41
NGix Avatar answered Sep 22 '22 21:09

NGix