How to get random objects from a QuerySet | Django

/ #Django


Sometimes you want to select a list of random objects from a QuerySet. Using a built in function from Python, this is a really simple task.

Let's say that we have a product model for storing products in an e-commerce. On the front-page of the e-commerce, we want to show 9 random products from the database.

To achieve this, we first get a list of products and then we randomize this.

import random

def frontpage(request):
    products = list(Product.objects.all())

    products = random.sample(products, 9)

    return render(request, 'front-page.html', {'products': products})

It's actually as simple as this!
First we import random from Python. Then we create a new view and get products from the database.

The function we use for randomizing the products only works with lists, so we need to convert the queryset to a list. A queryset is by default a dictionary.

When we have the list, we can randomize this by running "random.sample". We pass in the list and the number of products we want.

Build an e-commerce using Django

Want to learn how to build an e-commerce from scratch using Django?

Check out the playlist on my YouTube channel here: https://www.youtube.com/watch?v=bAG_Ia8LX-M&list=PLpyspNLjzwBmIDrDOaPkLLuy5YDDNW9SA

Comments

Dihfahsih Mugoya | Apr 14, 21 12:57

Thanks so much for this snippet, it was of great use to my script.

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.