Django gets a random object

I am trying to get a random object from model A

Now it works well with this code:

random_idx = random.randint(0, A.objects.count() - 1)
random_object = A.objects.all()[random_idx]

But I feel this code is better:

random_object = A.objects.order_by('?')[0]

Which one is better? Possible problem with deleted objects using the first code? Since, for example, I can have 10 objects, but object number 10 as id no longer exists? I did not understand something in A.objects.all () [random_idx]?

+4
source share
3 answers

Just looked at it. Line:

random_object = A.objects.order_by('?')[0]
It is reported that

shot down a lot of servers.

Unfortunately, Erwans code caused an error accessing multiple identifiers.

There is another short way to do this:

import random

items = Product.objects.all()

# change 3 to how many random items you want
random_items = random.sample(items, 3)
# if you want only a single random item
random_item = random.choice(items)

, .

+5

, , SQL, ORDER BY RANDOM(), , LIMIT.

- . , , random_idx ?

( , ). , id 1 MAX(id) , , - . , :

import random

# grab the max id in the database
max_id = A.objects.order_by('-id')[0].id

# grab a random possible id. we don't know if this id does exist in the database, though
random_id = random.randint(1, max_id + 1)

# return an object with that id, or the first object with an id greater than that one
# this is a fast lookup, because your primary key probably has a RANGE index.
random_object = A.objects.filter(id__gte=random_id)[0]
+3

:

pks = A.objects.values_list('pk', flat=True)
random_idx = randint(0, len(pks))
random_obj = A.objects.get(pk=pks[random_idx])

It works even if there are large spaces in pks, for example, if you want to filter a set of queries before selecting one of the remaining objects in random order.

+1
source

Source: https://habr.com/ru/post/1534679/


All Articles