Why wouldn’t we use Django ORM?
Using Django ORM is not suited for real database operations. Sure, it might look okay(ish) when you are only performing basic CRUD operations. But it will force you to perform database queries in the least optimized way (see N+1 SELECT issue)…
Its syntax is inconsistent, and its lack of support for many SQL features (including
JOIN) will make you go back to raw SQL queries as soon as things get tricky. Going back to raw SQL feels a bit like a failure when you are using an ORM, plus it is not easy to maintain.
So, what shall we do?
There is a lot of other ORMs for Python around:
- SQLAlchemy – has a lot of functionnalities, thanks to its huge community
- Peewee – very nicely written, lacks community
- Pony ORM – wonderful syntax, is not free
Of course there is more of them, but I focused on the most popular ones.
I chose SQLAlchemy, because it is free, has a huge set of features, supports many dialects (such as PostgreSQL, MySQL…), and the project is quite mature.
How do we use SQLAlchemy with Django?
First, setup Aldjemy from your virtual environment (this will install SQLAlchemy as well):
pip install aldjemy
(for Python 3 and PostgreSQL’s HSTORE support, install the package manually from this repository)
In your Django application’s settings script, add the following item to the
Now let’s imagine we have a module called
myapp.models, in which we defined three Django models (namely
Entry). The following declaration will make those entities available as SQLAlchemy models:
import myapp.models Blog = myapp.models.Blog.sa Author = myapp.models.Author.sa Entry = myapp.models.Entry.sa
To access SQLAlchemy’s session object, define this little function:
def Session(): from aldjemy.core import get_engine engine = get_engine() _Session = sessionmaker(bind=engine) return _Session()
Then simply call:
session = Session()
You can now perform SQLAlchemy queries within the Django ORM. Congratulations!