views:

2154

answers:

4

Has anyone used SQLAlchemy in addition to Django's ORM?

I'd like to use Django's ORM for object manipulation and SQLalchemy for complex queries (like those that require left outer joins).

Is it possible?

Note: I'm aware about django-sqlalchemy but the project doesn't seem to be production ready.

+3  A: 

I don't think it's good practice to use both. You should either:

  1. Use Django's ORM and use custom SQL where Django's built-in SQL generation doesn't meet your needs, or
  2. Use SQLAlchemy (which gives you finer control at the price of added complexity) and, if needed, use a declarative layer such as Elixir to make life a little easier.

Of course, if you need Django's admin, then the first of these approaches is recommended.

Vinay Sajip
Could you elaborate why it isn't a good practice to use both?
Piotr Czapla
It's not a hard and fast rule - it just doesn't usually make sense to have two components in a system which do the same thing. It's doable, of course. A lot depends on whether it's a hobby application, size of development team etc.
Vinay Sajip
+5  A: 

What I would do,

  1. Define the schema in Django orm, let it write the db via syncdb. You get the admin interface.

  2. In view1 you need a complex join


    def view1(request):
       import sqlalchemy
       data = sqlalchemy.complex_join_magic(...)
       ...
       payload = {'data': data, ...}
       return render_to_response('template', payload, ...)

uswaretech
+3  A: 

Jacob Kaplan-Moss admitted to typing "import sqlalchemy" from time to time. I may write a queryset adapter for sqlalchemy results in the not too distant future.

+3  A: 

I've done it before and it's fine. Use the SQLAlchemy feature where it can read in the schema so you don't need to declare your fields twice.

You can grab the connection settings from the settings, the only problem is stuff like the different flavours of postgres driver (e.g. with psyco and without).

It's worth it as the SQLAlchemy stuff is just so much nicer for stuff like joins.

Stuart Axon