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