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]?
Just looked at it. Line:
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)
, .
, , SQL, ORDER BY RANDOM(), , LIMIT.
ORDER BY RANDOM()
LIMIT
- . , , random_idx ?
( , ). , id 1 MAX(id) , , - . , :
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]
:
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.
Source: https://habr.com/ru/post/1534679/More articles:Stack Block Algorithm - algorithmPython numpy update from 1.6 to 1.8 - pythonMatrix multiplication in a block piece knitr - rMake the field mandatory if another field is marked in the form of Django - djangoRun a GWT project that is built by Gradle and works in Eclipse - eclipseTesting websockets server with protractor - angularjsMy installed EBS volume is not displayed - linuxDo ng-click, ng-mouseover etc. Create observers and slow down the page? Is this better than jQuery event binding? - javascriptMMDrawerController ั ัะฐัะบะฐะดัะพะฒะบะธ - objective-cMake a specific internal function visible to another assembly (i.e. not all visible internal elements) - c #All Articles