2👍
✅
If you have a manageable number of entries in the database (ie not thousands), this will work, and even though it hits the db twice it will probably be much more efficient than order_by('?')
.
import random
content_pks = Content.objects.values_list('pk', flat=True)
selected_pks = random.sample(content_pks, 30)
content_objects = Content.objects.filter(pk__in=selected_pks)
Source:stackexchange.com