0

So I want to have a feature like: "Random Post of the hour" for my website, where Post is some object from my model.

Having the DB choose a random post per request can get expensive so I don't want to pick a row on every request. I don't mind if different users have different "Random Post of the day".

I could go and just cache the query, but getting memcache involved with this feels like hacky overkill. So does creating a table and job for just this one value.

Is there a way to have some global variable that get periodically set in django?

Thank you!

Sandro
  • 2,219
  • 4
  • 27
  • 41
  • 1
    A related question: http://stackoverflow.com/questions/2680902/python-django-global-variables. The consensus seems to be that you shouldn't do that. If you deploy your app to a multi-process environment it'll be difficult not to use a shared storage of some kind anyway. – Eduardo Ivanec Mar 07 '12 at 01:45
  • Hmm interesting. So it looks like I want to use something from here: https://docs.djangoproject.com/en/1.3/topics/cache/#the-low-level-cache-api – Sandro Mar 07 '12 at 02:41
  • 1
    Yes, it's probably the way to go. In particular if the updates are sporadic and race conditions aren't an issue. – Eduardo Ivanec Mar 07 '12 at 02:47
  • Then (since I've got you now). What's the standard way to store a single value in Django? Having a table for a single row seems annoying, but I suppose it's fairly common. Is there a django idiom for this? – Sandro Mar 07 '12 at 03:30
  • 3
    The standard way is to use some K/V store (which is what a cache really is). – Burhan Khalid Mar 07 '12 at 04:12
  • Currently I am using MySQL as my DB backend. Switching over to a K/V for a single value seems like serious overkill. – Sandro Mar 07 '12 at 04:23
  • I would go ahead and create a simple KeyValue model with two fields, or something like that. I'm sure some people would argue over that, but if you don't want/need a full K/V store it seems reasonable. – Eduardo Ivanec Mar 07 '12 at 11:32
  • An example here: https://github.com/evanbeard/Django-Key-Value-Store/blob/master/kv_store/models.py – Eduardo Ivanec Mar 07 '12 at 11:33

1 Answers1

0

Went with Eduardo's Solution to use Memcached: https://docs.djangoproject.com/en/1.3/topics/cache/#the-low-level-cache-api

Sandro
  • 2,219
  • 4
  • 27
  • 41