0

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)
alireza
  • 45
  • 6
  • Does this answer your question? [How to pull a random record using Django's ORM?](https://stackoverflow.com/questions/962619/how-to-pull-a-random-record-using-djangos-orm) – AKX Nov 26 '21 at 13:01
  • actully I wnat to do it in the veiw not in the model . – alireza Nov 26 '21 at 13:06

3 Answers3

0

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_array.append(product.objects.filter(index=i))
0
products = product.objects.all().order_by('-id')[:50]
great_proposal1 = random.sample(list(products) , 12)

Hi . It worked with this code !

alireza
  • 45
  • 6
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 26 '21 at 23:55
0

Try this:

product.objects.order_by('?')[:12]

The '?' will "sort" randomly and "[:12]" will get only 12 objects.