You want to get a random Category. We will look at few alternate ways to do this.

The most straightforward way, you can order_by random and fetch the first record. It would look something like this.

defget_random():returnCategory.objects.order_by("?").first()

Note: order_by('?') queries may be expensive and slow, depending on the database backend you’re using. To test other methods, we need to insert one million records in Category table. Go to your db like with pythonmanage.pydbshell and run this.

get_random3 is about 283 time faster than get_random. get_random is the most generic way, but the technique in get_random3 will work unless you change changed the default way Django generates the id - autoincrementing integers, or there have been too many deletions.