Using Django Database Layer Outside of Django

Can one use the Django database layer outside of Django?

You just need to configure the Django settings before you do any calls, including importing your models. Something like this:

from django.conf import settings
settings.configure(
DATABASE_ENGINE = 'postgresql_psycopg2',
DATABASE_NAME = 'db_name',
DATABASE_USER = 'db_user',
DATABASE_PASSWORD = 'db_pass',
DATABASE_HOST = 'localhost',
DATABASE_PORT = '5432',
TIME_ZONE = 'America/New_York',
)

Again, be sure to run that code before running, e.g.:

from your_app.models import *

Then just use the DB API as usual.

Using only the DB part of Django

The short answer is: no, you can't use the Django ORM separately from Django.

The long answer is: yes, you can if you are willing to load large parts of Django along with it. For example, the database connection that is used by Django is opened when a request to Django occurs. This happens when a signal is sent so you could ostensibly send this signal to open the connection without using the specific request mechanism. Also, you'd need to setup the various applications and settings for the Django project.

Ultimately, it probably isn't worth your time. SQL Alchemy is a relatively well known Python ORM, which is actually more powerful than Django's anyway since it supports multiple database connections and connection pooling and other good stuff.


Edit: in response to James' criticism elsewhere, I will clarify what I described in my original post. While it is gratifying that a major Django contributor has called me out, I still think I'm right :)

First off, consider what needs to be done to use Django's ORM separate from any other part. You use one of the methods described by James for doing a basic setup of Django. But a number of these methods don't allow for using the syncdb command, which is required to create the tables for your models. A settings.py file is needed for this, with variables not just for DATABASE_*, but also INSTALLED_APPLICATIONS with the correct paths to all models.py files.

It is possible to roll your own solution to use syncdb without a settings.py, but it requires some advanced knowledge of Django. Of course, you don't need to use syncdb; the tables can be created independently of the models. But it is an aspect of the ORM that is not available unless you put some effort into setup.

Secondly, consider how you would create your queries to the DB with the standard Model.objects.filter() call. If this is done as part of a view, it's very simple: construct the QuerySet and view the instances. For example:

tag_query = Tag.objects.filter( name='stackoverflow' )
if( tag_query.count() > 0 ):
tag = tag_query[0]
tag.name = 'stackoverflowed'
tag.save()

Nice, simple and clean. Now, without the crutch of Django's request/response chaining system, you need to initialise the database connection, make the query, then close the connection. So the above example becomes:

from django.db import reset_queries, close_connection, _rollback_on_exception
reset_queries()
try:
tag_query = Tag.objects.filter( name='stackoverflow' )
if( tag_query.count() > 0 ):
tag = tag_query[0]
tag.name = 'stackoverflowed'
tag.save()
except:
_rollback_on_exception()
finally:
close_connection()

The database connection management can also be done via Django signals. All of the above is defined in django/db/init.py. Other ORMs also have this sort of connection management, but you don't need to dig into their source to find out how to do it. SQL Alchemy's connection management system is documented in the tutorials and elsewhere.

Finally, you need to keep in mind that the database connection object is local to the current thread at all times, which may or may not limit you depending on your requirements. If your application is not stateless, like Django, but persistent, you may hit threading issues.

In conclusion, it is a matter of opinion. In my opinion, both the limitations of, and the setup required for, Django's ORM separate from the framework is too much of a liability. There are perfectly viable dedicated ORM solutions available elsewhere that are designed for library usage. Django's is not.

Don't think that all of the above shows I dislike Django and all it's workings, I really do like Django a lot! But I'm realistic about what it's capabilities are and being an ORM library is not one of them.

P.S. Multiple database connection support is being worked on. But it's not there now.

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

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])


Related Topics



Leave a reply



Submit