Reputation: 11763
I'm new to Django, but the application that I have in mind might end up having URLs that look like this:
http://mysite/compare/id_1/id_2
Where "id_1" and "id_2" are identifiers of two distinct Model objects. In the handler for "compare" I'd like to asynchronously, and in parallel, query and retrieve objects id_1 and id_2.
Is there any way to do this using a standard Django syntax? I'm hoping for pseudocode that ends up looking something like this:
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...
Upvotes: 23
Views: 6832
Reputation: 97892
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))
Upvotes: 11