3

I've got a query set up that puts 28 random records from a database into a JSON response. This page is hit often, every few seconds, but is currently too slow for my liking.

In the JSON response I have:

  • ID's
  • Usernames
  • a Base64 thumbnail

These all come from three linked tables.
I'd be keen to hear of some other solutions, instead of users simply hitting a page, looking up 28 random records and spitting back the response. One idea I had:

  • Have a process running that creates a cached page every 30 seconds or so with the JSON response.

Is this a good option? If so, I'd be keen to hear how this would be done.

Thanks again,
Hope everyone is well

Danny
  • 199
  • 10
  • 2
    Instead of mucking around at the controller layer, first check that the sql query is optimal. It surely doesn't *seem* like it, if fetching 28 records is to slow. For example, mysql's "order by rand()" construct is exceptionally slow and should be avoided. – Björn Lindqvist Aug 23 '11 at 13:44

2 Answers2

4

Django supports a variety of caching methods, both built-in and memcached. I would select one of the methods in the documentation, and create a specific view for your json response. You could then use the @cache_page decorator and specify a particular time.

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def my_view(request):
    ...

https://docs.djangoproject.com/en/1.3/topics/cache/

shawnwall
  • 4,549
  • 1
  • 27
  • 38
0

If the tables are linked via foreign key, maybe using select_related? From the link, the example they give (you'll need to scroll down a bit):

>>> e = Entry.objects.select_related().get(id=2)
>>> print e.blog  # Doesn't hit the database; uses cached version.
>>> print e.blog  # Doesn't hit the database; uses cached version.

I'm not sure about three tables, but it works well for two.

Evan Porter
  • 2,987
  • 3
  • 32
  • 44
  • I could probably cut down the tables to one if needed, but the main point is people are hitting a database of a million records for only 28 random records. Is it ok to simply hit the database each time, or create a static JSON response every 30 seconds. – Danny Aug 23 '11 at 11:28