列中的最后一条记录,SQLALCHEMY

Sal*_*rsi 5 python sqlalchemy

我试图使用这个获取我专栏中的最后一条记录

 ObjectRes.query.order_by('-id').first()
Run Code Online (Sandbox Code Playgroud)

但结果是:无

我尝试使用所有其他查询,唯一有效的是

obj = ObjectRes.query.all()
return str(obj[-1].id)
Run Code Online (Sandbox Code Playgroud)

查询太繁重,需要在 Pythonanywhere 上使用更轻量级的查询。谢谢

dav*_*ing 8

Columns in SQLAlchemy models have methods attached to produce this behaviour. To order by ID descending, do this:

descending = Object.query.order_by(Object.id.desc())
last_item = descending.first()
Run Code Online (Sandbox Code Playgroud)

Specifying Object.field is the clearest syntax for choosing a field to order by, and all columns / model attributes should support .desc() or .asc()

You can of course do this in a one liner as well:

last_item = Object.query.order_by(Object.id.desc()).first()
Run Code Online (Sandbox Code Playgroud)