异步Django模型查询可能吗?
我刚开始学习Django,但我想的这个应用可能会有这样的URL:
http://mysite/compare/id_1/id_2
其中“id_1”和“id_2”是两个不同模型对象的标识符。在处理“compare”的时候,我想要异步并行地查询并获取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 个回答
11
你提到的那种严格的异步操作其实并不存在,不过我觉得你可以通过使用 Django 的 in_bulk 查询操作来达到类似的效果。这个操作可以接受一个 ID 列表来进行查询。
在 urls.py
文件中可以这样写:
urlpatterns = patterns('',
(r'^compare/(\d+)/(\d+)/$', 'my.compareview'),
)
在视图(view)中可以这样写:
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))