I am building an application that tracks karma that users give to each other. I want to be able to build a leaderboard over a rolling 7-day period and a list of people who have given you the most karma over a rolling 7-day period. I have come up the following model:
class KarmaAction(models.Model):
user = models.ForeignKey(User)
sender = models.ForeignKey(User)
karma = models.IntegerField()
created_at = models.IntegerField()
First off, will the above model scale well as the number of users grows? I am thinking of deleting any rows that are over 7 days old. Secondly, I want to know how I can create a list of senders with the corresponding sum of the karma they have given the last few days. Maybe it would look something like this:
supporters = {'User 1': 14, 'User 2': 12, 'User 3': 7, 'User 4': 2}
Is there any way to do this with the Django ORM?
The model seems reasonable to me; I don’t really see another way to do it. You need all of the information in there to be able to fulfill your requirements, anyway. (Though
created_atshould probably be aDateTimeField?) If it ends up too slow, you’ll probably just have to add aggressive caching.You can do something like (untested, but I think it should work)
which will use the
valuesto group by uniquesenders and then sum theirkarmavalues.I added the
order_byto make sure that if there’s a default ordering, it gets cleared and doesn’t interfere with the grouping. It also makes it easy to just get the topnsenders of karma, though, by just adding e.g.[:5]to the end — if you make it-total_sent, of course :).I don’t think the
filtercauses this problem, but I’m not positive without testing.