[英]Performing Sort on half Column Sqlalchemy
I have a Entity (Table) Name Program and in Program there is a field (Column) Session. 我有一个实体(表)名称程序,在程序中有一个字段(列)会话。 Session is a string field as is stored in following way.
会话是一个字符串字段,其存储方式如下。 2011 - Fall
2011年-秋季
I only want to sort on year part. 我只想按年份排序。 Is this possible.
这可能吗。 I'm using sqlalchemy.
我正在使用sqlalchemy。
See documentation for SQL and Generic Functions
. 请参阅有关
SQL and Generic Functions
文档。 For postgres
it is a substring
function which you use to remove the first 7 character from the string. 对于
postgres
它是一个substring
函数,可用于从字符串中删除前7个字符。 The final query might look like: 最终查询可能类似于:
from sqlachemy import func
expr = func.substring(Program.session, 8) # for postgresql
programs = (
session.query(Program, expr.label("season"))
.order_by(expr.desc())
.all()
)
You can sort using desc()
or asc()
methods. 您可以使用
desc()
或asc()
方法进行排序。 Since you have your string in the format of YEAR - SEASON
, this will sort your data like so (assuming descending order): 由于您的字符串格式为
YEAR - SEASON
,因此将对数据进行排序(假设降序排列):
2019 - Spring
2019 - Fall
2018 - Spring
2018 - Fall
2017 - Spring
2017 - Fall
2016 - Spring
2016 - Fall
2015 - Spring
2015 - Fall
2014 - Spring
2014 - Fall
...
This can be seen with the following example: 可以通过以下示例看到这一点:
from sqlalchemy import Column, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Program(Base):
__tablename__ = 'program'
session = Column(String(250), primary_key=True)
engine = create_engine('sqlite:///program.db')
Base.metadata.create_all(engine)
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
for x in range(2000, 2020):
session.add(Program(session="{} - Fall".format(x)))
session.add(Program(session="{} - Spring".format(x)))
session.commit()
programs = session.query(Program).order_by(Program.session.desc()).all()
for x in programs:
print x.session
This creates a <Year> - Fall
and <Year> - Spring
entry for each year between 2000 and 2019. It then runs a simple query asking for all of this data back in descending order. 这将为2000年至2019年之间的每年创建一个
<Year> - Fall
和<Year> - Spring
条目。然后运行一个简单的查询,以降序返回所有这些数据。 The first several lines are at the top of this answer. 前几行在此答案的顶部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.