How can i filter 12 random objects from a model in django . I tried to do this but It does not work and It just returned me 1 object.
max = product.objects.aggregate(id = Max('id'))
max_p = int(max['id'])
l = []
for s in range(1 , 13):
l.append(random.randint(1 , max_p))
for i in l:
great_proposal = product.objects.filter(id=i)
CodePudding user response:
I'm pretty sure the code is correct, but maybe you did not realize that you're just using great_proposal
as variable to save the output, which is not an array, and therefore only returns one output.
Try:
result_array = []
for i in l:
result.append(product.objects.filter(index=i))
CodePudding user response:
products = product.objects.all().order_by('-id')[:50]
great_proposal1 = random.sample(list(products) , 12)
Hi . It worked with this code !