效率太低了
时间: 2023-07-19 07:20:37 浏览: 56
确实,使用 `order_by(func.random())` 或者 `order_by(func.rand())` 随机获取数据的效率比较低,因为它会对所有的数据进行排序,如果数据量很大,那么排序的开销就非常大。
有一种更高效的方式是使用 `func.random()` 和 `offset()` 函数结合使用,先随机生成一个偏移量,再获取偏移量之后的十条数据。示例代码如下:
```python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:password@localhost:5432/your_database'
db = SQLAlchemy(app)
class YourModel(db.Model):
# 定义模型类
# 获取数据总数
total = db.session.query(YourModel).count()
# 随机获取十条数据
offset = func.floor(func.random() * total).cast('integer')
result = db.session.query(YourModel).offset(offset).limit(10).all()
```
其中,`YourModel` 是你的模型类,`func.random()` 表示随机生成一个浮点数,`total` 表示数据总数,`func.floor()` 表示向下取整,`cast('integer')` 表示强制转换为整型。`offset` 表示偏移量,`db.session.query(YourModel).offset(offset).limit(10).all()` 表示获取偏移量之后的十条数据。这种方式不需要对所有数据进行排序,效率比较高。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)