I want to query 3 Random Products from the Database everytime only 3

Viewed 93
y = (Product.objects.all()).count()
    x = random.randint(3,y)
    prouct1 = Product.objects.get(id = x+1)
    prouct2 = Product.objects.get(id = x-1)
    prouct3 = Product.objects.get(id = x-2)

I want to obtain 3 random products everytime i run a function initially i use the above method But the problem with this is If i delete a object Then i get the error i dont want that thing to happen obviously i can run more checks but i feel there is some simple way to do that The objective is to Get the random object from the database every time the page is renderd

2 Answers

Work with OFFSET … LIMIT … instead:

qs = Product.objects.all()
n = qs.count()
x0, x1, x2 = random.sample(range(n), 3)
product0 = qs[x0]
product1 = qs[x1]
product2 = qs[x2]

this requires that there are at least three items in the Product table, and will make four queries: one for the count and three for the individual products. It will also guarantee that the three products are distinct.

If the table is not that large, you can sample from the list of primary keys and then fetch three items:

pks = Product.objects.values_list('pk', flat=True)
product0, product1, product2 = Product.objects.filter(pk__in=random.sample(pks, 3))

This will make two queries: one to load all primary keys, and another to fetch the three products in bulk. This is more extensible if the number of products you want to fetch increases since fetching ten products for example, will still require two queries.

Simply you can fetch random product by using .order_by('?'):

ran_prod = Product.objects.all().order_by('?')[:3]

Note :

order_by('?') queries may be expensive and slow, depending on the database backend you’re using.

Related