[Django]-How to use Django 1.8.5 ORM without creating a django project?

12πŸ‘

βœ…

Django 1.11 documentation on how the applications are loaded

For latest django version project structure would be-

|--myproject
|--main.py
|--manage.py
|--myapp
|   |--models.py
|   |--views.py
|   |--admin.py
|   |--apps.py
|   |--__init__.py
|   |--migrations
|--myproject
|   |--settings.py
|   |--urls.py
|   |--wsgi.py
|   |--__init__.py

You would still need manage.py to run migrations, main.py is your standalone script

# main.py
import os
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
django.setup()
from myapp.models import MyModel
print(MyModel.objects.all()[0])

35πŸ‘

There are a lot of answers out there that work with older versions of Django, but Django is constantly updating and in my research I found no viable answer for Django 1.8/1.9, so I had to roll my own. Here’s how you do it:

Project Structure:

β”œβ”€β”€ data
β”‚Β Β  β”œβ”€β”€ __init__.py
β”‚Β Β  β”œβ”€β”€ migrations
β”‚Β Β  β”‚Β Β  └── __init__.py
β”‚Β Β  └── models.py
β”œβ”€β”€ main.py
β”œβ”€β”€ manage.py
└── settings.py

The data directory and migrations directory contain empty __init__.py files. The sample models.py file reads as follows:

# models.py
from django.db import models

class User(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField(max_length=255)

The manage.py file is the typical Django manage.py file. Just be sure to change the settings param in os.environ.setdefault if you copy it from a fresh django-admin startproject command:

#!/usr/bin/env python
# manage.py
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

The settings.py file requires 3 settings: DATABASES, INSTALLED_APPS, and SECRET_KEY. Refer to Django docs for DBs that aren’t SQLite:

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'sqlite.db',
    }
}

INSTALLED_APPS = (
    'data',
    )

SECRET_KEY = 'REPLACE_ME'

The real trick is in main.py, which will be where you can code against your models. Apparently you have to use wsgi to get things working with these two lines:

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Here’s a sample main.py:

# main.py
# Django specific settings
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")

### Have to do this for it to work in 1.9.x!
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
#############

# Your application specific imports
from data.models import *

#Add user
user = User(name="someone", email="someone@example.com")
user.save()

# Application logic
first_user = User.objects.all()[0]

print(first_user.name)
print(first_user.email)

This project along with this post were helpful starting points for me to find the answer, and my pull request with working code for Django 1.9 was merged, so you can grab the code from masnun’s repo now. If you know of a better way, please submit a pull request.

πŸ‘€mattmc3

11πŸ‘

import os
from django.conf import settings
from django.apps import apps

conf = {
    'INSTALLED_APPS': [
        'Demo'
    ],
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join('.', 'db.sqlite3'),
        }
    }
}

settings.configure(**conf)
apps.populate(settings.INSTALLED_APPS)

Test on django 1.11.x

πŸ‘€Hai Hu

2πŸ‘

This worked for me:

import os
# replace project_name with your own project name
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")
django.setup()
from core.models import Customer,Jobs,Payments

# Your script code
πŸ‘€obayhan

-1πŸ‘

I had to add import django, and then this worked.

πŸ‘€Joel Aufrecht

Leave a comment