[Django]-Django pagination random: order_by('?')

2๐Ÿ‘

โœ…

i think this really good answer will be useful to you: How to have a "random" order on a set of objects with paging in Django?

basically he suggests to cache the list of objects and refer to it with a session variable, so it can be maintained between the pages (using django pagination).

or you could manually randomize the list and pass a seed to maintain the randomification for the same user!

๐Ÿ‘คcaesarsol

4๐Ÿ‘

I ran into the same problem recently where I didnโ€™t want to have to cache all the results.
What I did to resolve this was a combination of .extra() and raw().
This is what it looks like:

raw_sql = str(queryset.extra(select={'sort_key': 'random()'})
                          .order_by('sort_key').query)
set_seed = "SELECT setseed(%s);" % float(random_seed)
queryset = self.model.objects.raw(set_seed + raw_sql)

I believe this will only work for postgres. Doing a similar thing in MySQL is probably simpler since you can pass the seed directly to RAND(123).
The seed can be stored in the session/a cookie/your frontend in the case of ajax calls.

Warning โ€“ There is a better way
This is actually a very slow operation. I found this blog post describes a very good method both for retrieving a single result as well as sets of results.
In this case the seed will be used in your local random number generator.

๐Ÿ‘คGeekfish

1๐Ÿ‘

The best way to achive this is to use some pagination APP like:

Personally i use the first one, it integrates pretty well with Haystack.

 """ EXAMPLE: (django-pagination) """
     #paginate 10 results.

    {% autopaginate my_query 10 %}
๐Ÿ‘คAdrian Lopez

Leave a comment