fastapi / sqlmodel

SQL databases in Python, designed for simplicity, compatibility, and robustness.
https://sqlmodel.tiangolo.com/
MIT License
14.54k stars 663 forks source link

Is there a way to get a random record and/or order a query randomly with SQLmodel? #277

Open bolinocroustibat opened 2 years ago

bolinocroustibat commented 2 years ago

First Check

Commit to Help

Example Code

random_user = select(User).order_by('?').limit(1)

Description

Is there a way to get a random record and/or order a query randomly, like an equivalent to Django .order_by('?') or to SQLalchemy .order_by(func.rand()) for MySQL?

Operating System

Linux

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

3.9

Additional Context

No response

mgurg commented 2 years ago

Try this:

from sqlalchemy import func

task = session.exec(select(Tasks).order_by(func.random())).first()
johnziebro commented 2 years ago

I ended up here looking at how to find the last record. Docs and issues don't have info on this. Thanks for the direction.

Using the code from this issue finding the last record (based on the primary key), you just have to sort the results in descending order with sqlalchemy imports and return first as well:

from sqlalchemy import asc, desc

task = session.exec(select(Tasks).order_by(desc(Tasks.id)).first()