简体   繁体   中英

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

I only want to sort on year part. Is this possible. I'm using sqlalchemy.

See documentation for SQL and Generic Functions . For postgres it is a substring function which you use to remove the first 7 character from the string. 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. Since you have your string in the format of YEAR - SEASON , this will sort your data like so (assuming descending order):

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. The first several lines are at the top of this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM