代码之家  ›  专栏  ›  技术社区  ›  slacy

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

  •  21
  • slacy  · 技术社区  · 15 年前

    我刚接触Django,但我想到的应用程序可能最终会有如下URL:

    http://mysite/compare/id_1/id_2
    

    其中“id_1”和“id_2”是两个不同模型对象的标识符。在“比较”的处理程序中,我希望异步并并行地查询和检索对象i d_1和i d_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 回复  |  直到 15 年前
        1
  •  11
  •   guettli    13 年前

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