mjaz
mjaz

Reputation: 471

Django and SQL question: Reduce number of database hits

For one of my clients, I am generating a clients list from the Django Admin. It splits the clients by status: current, acquired, and past.

Currently, the view code for that list is as follows:

def clients_list(request):
current_clients = Client.objects.all().filter(status='current')[:10]
acquired_clients = Client.objects.all().filter(status='acquired')[:10]
past_clients = Client.objects.all().filter(status='past')[:10]

return render_to_response('clients/list.html', {
    'current_clients': current_clients,
    'acquired_clients': acquired_clients,
    'past_clients': past_clients
})

Now, I know this isn't ideal as it hits the database three times when I'm pretty sure there's a way to do it with only one query. Is it possible to refactor this code so that it only hits the database once and uses Python to split the result into those three variables? Or am I just stressing too much over a trivial part of my application?

Thanks,

Matt

Upvotes: 0

Views: 512

Answers (1)

Paul Bissex
Paul Bissex

Reputation: 1704

Unless you've profiled your app and know this is a serious bottleneck, I think you've got the answer: "just stressing too much".

You could fetch your data in a single ORM statement using Q objects...

clients = Client.objects.filter(Q(status='current')|Q(status='acquired')|Q(status='past'))[:30]

...but then you'd have all three statuses in one queryset, and probably wouldn't have ten of each, and you'd still have to separate them for your template.

Upvotes: 2

Related Questions