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

标签 python mysql django multithreading django-models

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

http://mysite/compare/id_1/id_2

其中“id_1”和“id_2”是两个不同模型对象的标识符。在“比较”的处理程序中,我想异步并行地查询和检索对象 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...

最佳答案

没有您所描述的严格异步操作,但我认为您可以通过使用 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))      

关于python - 异步 Django 模型查询是否可行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/918298/

相关文章:

python - 向后读取 gzip 文件

python - 同时从两个列表中弹出值

通过ssh执行Mysql查询

php - 为什么 str_replace 不替换这个字符串?

python - Django 中的可排序表格

python - 如何从 Django 中的查询集中检索值?

python - 在制作新图时再次绘制旧数据(对于较早的图)

python - 多面体的 Delaunay 三角化(Python)

python - 无法为 Django 和 Mysql 启动 docker 构建

python - Django 使用 crispy 表单用 css 渲染表单字段