[Django]-Are asynchronous Django model queries possible?

11👍

There aren’t strictly asynchronous operations as you’ve described, but I think you can achieve the same effect by using django’s in_bulk query operator, which takes a list of ids to query.

Something like this for the urls.py:

urlpatterns = patterns('',
    (r'^compare/(\d+)/(\d+)/$', 'my.compareview'),
)

And this for the 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))      

Leave a comment