如何在Django / postgreSQL中从数据库中获取一个随机项? [英] How to grab one random item from a database in Django/postgreSQL?

查看:129
本文介绍了如何在Django / postgreSQL中从数据库中获取一个随机项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我得到了database.objects.all()和database.objects.get('name'),但是如何从数据库中获得一个随机项。我在尝试弄清楚如何从一个随机项中选择它时遇到了麻烦。

So i got the database.objects.all() and database.objects.get('name') but how would i got about getting one random item from the database. I'm having trouble trying to figure out how to get it ot select one random item.

推荐答案

从一个随机元素中选择一个随机元素列出所有数据库对象不是一个很好的解决方案,因为检索数据库的所有元素都会对性能产生很大影响,也不会像上述那样使用 order_by('?') django文档中。

Selecting a random element from a list of all database objects isn't a goog solution as retrieving all elements of the database can have a big impact on performance, neither is using order_by('?') as mentioned in the django documentation.

最好的解决方案应该是检索具有随机索引的元素:

The best solution should be to retrieve an element with a random index:

import random

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

这篇关于如何在Django / postgreSQL中从数据库中获取一个随机项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆