SQLAlchemy 按降序排序?
如何在 SQLAlchemy 查询中使用 ORDER BY descending
,如下所示?
此查询有效,但按升序返回它们:
query = (model.Session.query(model.Entry)
.join(model.ClassificationItem)
.join(model.EnumerationValue)
.filter_by(id=c.row.id)
.order_by(model.Entry.amount) # This row :)
)
如果我尝试:
.order_by(desc(model.Entry.amount))
然后我得到:NameError:全局名称'desc'未定义
。
How can I use ORDER BY descending
in a SQLAlchemy query like the following?
This query works, but returns them in ascending order:
query = (model.Session.query(model.Entry)
.join(model.ClassificationItem)
.join(model.EnumerationValue)
.filter_by(id=c.row.id)
.order_by(model.Entry.amount) # This row :)
)
If I try:
.order_by(desc(model.Entry.amount))
then I get: NameError: global name 'desc' is not defined
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
仅供参考,您还可以将这些内容指定为列属性。例如,我可能会这样做:
这很方便,因为它避免了导入,并且您可以在其他地方使用它,例如在关系定义中等。
有关更多信息,您可以参考此< a href="https://docs.sqlalchemy.org/en/14/core/sqlelement.html#sqlalchemy.sql.expression.desc" rel="noreferrer">SQLAlchemy 1.4 文档
Just as an FYI, you can also specify those things as column attributes. For instance, I might have done:
This is handy since it avoids an
import
, and you can use it on other places such as in a relation definition, etc.For more information, you can refer this SQLAlchemy 1.4 Documentation
用法来自@jpmc26
Usage from @jpmc26
您可以做的另一件事是:
这将导致:ORDER BY name desc。这里的缺点是 order by 使用的显式列名。
One other thing you might do is:
This will result in: ORDER BY name desc. The disadvantage here is the explicit column name used in order by.
您可以在查询中使用
.desc()
函数,如下所示:这将按金额降序排列
或
使用 SQLAlchemy 的 desc 函数:
对于官方文档,请使用 链接 或检查以下代码片段:
You can use
.desc()
function in your query just like this:This will order by amount in descending order
or
Use of desc function of SQLAlchemy:
For official docs please use the link or check below snippet:
您可以尝试:
.order_by(ClientTotal.id.desc())
You can try:
.order_by(ClientTotal.id.desc())
补充@Radu的回答,就像在SQL中一样,如果你有很多具有相同属性的表,你可以在参数中添加表名。
Complementary at @Radu answer, As in SQL, you can add the table name in the parameter if you have many table with the same attribute.