21👍
✅
You can’t reorder a query once a slice has been taken, so use different approach
import random
items = sorted(MyModel.objects.all().order_by('nr')[:10], key=lambda x: random.random())
33👍
Curiously, this not very well documented feature works:
Country.objects.order_by('?')
source: http://www.jpstacey.info/blog/2008/09/03/random-ordering-of-query-results-in-django
Astonishingly, the existing documentation has very little Google juice, unless you search for “randomly” rather than “random”.
- [Django]-Django migration fails with "__fake__.DoesNotExist: Permission matching query does not exist."
- [Django]-What does 'many = True' do in Django Rest FrameWork?
- [Django]-Django Admin Form for Many to many relationship
18👍
OK, you can’t re-order a queryset after you’ve pulled it in, but you can do this instead
import random
items = list(MyModel.objects.all().order_by('nr')[:10])
random.shuffle(items)
- [Django]-Django annotation with nested filter
- [Django]-ValueError: The field admin.LogEntry.user was declared with a lazy reference
- [Django]-Equivalent of PHP "echo something; exit();" with Python/Django?
Source:stackexchange.com