异步Django模型查询是否可行?

时间:2009-05-27 22:19:00

标签: python mysql django multithreading django-models

我是Django的新手,但我想到的应用程序最终可能会显示如下所示的网址:

http://mysite/compare/id_1/id_2

其中“id_1”和“id_2”是两个不同的Model对象的标识符。在“比较”的处理程序中,我想异步,并行地查询和检索对象id_1和id_2。

有没有办法使用标准的Django语法?我希望伪代码最终看起来像这样:

import django.async 

# Issue the model query, but set it up asynchronously.  
# The next 2 lines don't actually touch my database 
o1 = Object(id=id_1).async_fetch()
o2 = Object(id=id_2).async_fetch()

# Now that I know what I want to query, fire off a fetch to do them all
# in parallel, and wait for all queries to finish before proceeding. 

async.Execute((o2,o2))

# Now the code can use data from o1 and o2 below...

1 个答案:

答案 0 :(得分:11)

没有像你所描述的那样严格的异步操作,但我认为你可以通过使用django的in_bulk查询运算符来实现相同的效果,该运算符需要一组id来查询。

urls.py

这样的内容
urlpatterns = patterns('',
    (r'^compare/(\d+)/(\d+)/$', 'my.compareview'),
)

以下是观点:

def compareview(request, id1, id2):
    # in_bulk returns a dict: { obj_id1: <MyModel instance>, 
    #                           obj_id2: <MyModel instance> }
    # the SQL pulls all at once, rather than sequentially... arguably
    # better than async as it pulls in one DB hit, rather than two
    # happening at the same time
    comparables = MyModel.objects.in_bulk([id1, id2])
    o1, o2 = (comparables.get(id1), comparables.get(id2))