How do I get two distinct random records using Django? I've seen questions about how to get one but I need to get two random records and they must differ.
+5
A:
Object.objects.order_by('?')[:2]
This would return two random-ordered records. You can add
distinct()
if there are records with the same value in your dataset.
wsorenson
2009-11-13 19:31:01
+10
A:
If you specify the random operator in the ORM I'm pretty sure it will give you two distinct random results won't it?
MyModel.objects.order_by('?')[:2] # 2 random results.
Bartek
2009-11-13 19:31:24
Yes this works. I was adding .get() at the end which was causing the error.
Matt McCormick
2009-11-13 20:32:04