1

I have a model which has an IntegerField. this field may change after creation of object. I wanna use it for the "trend" part in my project, like those objects with the larger number must shown at top. so what is the best way (efficient) to do this. my current idea is:

class Map(models.Model):
    rank = models.IntegerField()

and later use it like this:

sorted_list = Map.objects.order_by("-rank")[:50]

is this a good idea even if there are many requests for the trend page?

1 Answers1

2

Yes, this is efficient because the database is doing the sorting work. Just ensure you have an index on the rank column, or it will get very slow as row count increases.

If there are going to be many hits, cache the result with an appropriate timeout.

Tim Nyborg
  • 1,599
  • 1
  • 9
  • 16
  • Thanks, but I was thinking about some kind of already sorted thing. like the max heap in data structures. which it doesn't need to sort it every single time cause it's already sorted. and should I cache things by defining models? or if there is a link for how to do this I would be appreciated. – Esmail Mahjoor Mar 17 '21 at 20:04
  • 1
    Well, indexes are an 'already sorted thing'. It's a parallel data structure in the database ordering the data according to the specified column, so it doesn't need to be sorted each time. There are a number of approaches to caching, depending on exactly how you want it to function - how often should the result be refreshed, etc. The simplest may be to create a utility function outside the model, a `def get_top_maps()` which internally uses cache.get() and cache.set() to save the results for seconds or minutes at a time. See https://docs.djangoproject.com/en/3.1/topics/cache/#basic-usage – Tim Nyborg Mar 17 '21 at 21:03