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!
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.
- [Django]-Use pyExcelerator to generate dynamic Excel file with Django. Ensure unique temporary filename
- [Django]-Problem installing pyscopg2 on Mac OS X
- [Django]-Named JSON array in Django REST Framework
- [Django]-PyCharm doesn't recognise my VirtualEnv installed modules
- [Django]-Google app engine + python (django) deployment error: Error loading MySQLdb module
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 %}