Menu Close

How to pull a random record using Python Django’s ORM?

To pull a random record using Python Django’s ORM, we can use the first method with order_by.

For instance, we write

MyModel.objects.order_by('?').first()

to call order_by with '?' to return the MyModel objects in random order.

And then we call first to pick the first one.

Posted in Python, Python Answers