Best way to integrate SqlAlchemy into a Django project

Viewed 13643

I changed my Django application to use SQLAlchemy, and it works now.

But I'm wondering where I should put these lines:

engine = sqlalchemy.create_engine(settings.DATABASE_URL)
Session = sqlalchemy.orm.sessionmaker(bind=engine)
session = Session()

The reason I'm asking is because I want to use SQLAlchemy at many place, and I don't think its correct/powerful/well-written to call this three lines everytime I need to use the database.

The place I will require SA is :

  • In my views, of course
  • In some middleware I wrote
  • In my models. Like in get_all_tags for a BlogPost Model.

What I think would be correct, is to get the session, by re-connecting to the database if the session is closed, or just returning the current, connected session if exists.

How can I use SQLAlchemy correctly with my Django apps?

Thanks for your help!

Note: I already followed this tutorial to implement SA into my Django application, but this one doesn't tell me exactly where to put those 3 lines (http://lethain.com/entry/2008/jul/23/replacing-django-s-orm-with-sqlalchemy/).

1 Answers
Related