Asked By – kender
I have a model that represents paintings I present on my site. On the main webpage I’d like to show some of them: newest, one that was not visited for most time, most popular one and a random one.
I’m using Django 1.0.2.
While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:
number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index)
It doesn’t look like something I’d like to have in my view tho – this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won’t cover me all the possible key values) and probably lots of other things.
Any other options how I can do it, preferably somehow inside the model abstraction?
Now we will see solution for issue: How to pull a random record using Django’s ORM?
order_by('?') will kill the db server on the second day in production. A better way is something like what is described in Getting a random row from a relational database.
from django.db.models.aggregates import Count from random import randint class PaintingManager(models.Manager): def random(self): count = self.aggregate(count=Count('id'))['count'] random_index = randint(0, count - 1) return self.all()[random_index]