开发者

Sqlalchemy for performing complex queries in Django project

What is the best option to use sqlalchemy for performing complex queries in Django project? I have found tranquil , but it does not look like a project with many users... Any suggestions?

Reason: I have 30-40 RawQueries across project and maintaining these queries is painful... I think SQLAlchemy can provide much better experience in this case.

UPDATE.

T开发者_如何学编程he main goal to achieve is to write some big complex query once and be able to refine it later as I need:

q = get_big_complex_sqlalachemy_query()
mine = q.filter_by(table.c.created_by_id=1)
closed = q.filter_by(table.c.is_closed=True)

The biggest problem with Django and SQLAlchemy is transaction management. If you use big transactions (one transaction per request) SQLAlchemy does not see any changes until you commit them (happy debugging :). So I wrote custom connection pool for SQLAlchemy to use Django connection. This is not ideal too (now there are problems in tests, because SQLAlchemy likes to wrap every select in transaction and I still don't know how to disable this), but it looks better.


While I'm not familiar with tranquil, I can say the way to use sqlalchemy in django is to... use sqlalchemy... in django!

When I've used sqlalchemy in django projects in the past, I've usually been reading in data from external data sources (stuff not managed by the django ORM). With that in mind, I tend to use the SqlSoup extension which doesn't require you to explicitly declare the structure of your data. This might be good for you too, since I'm guessing you don't want to write all your models twice in 2 different ORMs.

One other tip: if you don't need sqlalchemy for every view, don't open the connection in your settings module. Put your sqlalchemy code (including the connection creation) in its own module or package -- keep it as isolated as possible. Only import the module and create the connection when you really need it.

All of this depends on what your goal is though. Are your queries mainly read, or are you wanting to write as well? I don't really have a sense of what it is you're trying to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜