Django 获取一个随机对象 [英] Django get a random object
问题描述
我正在尝试从模型 A 中获取一个随机对象
I am trying to get a random object from a model A
目前,它与此代码运行良好:
For now, it is working 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]
哪个最好?使用第一个代码删除对象的可能问题?因为,例如,我可以有 10 个对象,但 id 为 10 的对象不再存在?我是否误解了 A.objects.all()[random_idx] 中的某些内容?
Which one is the best? Possible problem with deleted objects using the first code? Because, for example, I can have 10 objects but the object with the number 10 as id, is not existing anymore? Did I have misunderstood something in A.objects.all()[random_idx] ?
推荐答案
刚刚在看这个.行:
random_object = A.objects.order_by('?')[0]
据报道已经关闭了许多服务器.
has reportedly brought down many servers.
不幸的是,Erwans 代码导致访问非顺序 ID 时出错.
Unfortunately Erwans code caused an error on accessing non-sequential ids.
还有一种简单的方法可以做到这一点:
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)
这样做的好处是它可以毫无错误地处理非顺序 ID.
The good thing about this is that it handles non-sequential ids without error.
这篇关于Django 获取一个随机对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!