SQLAlchemy按DateTime排序:asc by Date,desc by Time

时间:2018-03-04 15:27:20

标签: python sqlite sqlalchemy

这是一个使用python 3.6和SQLAlchemy 1.2.4的MWE。我的后端是SQLite 3.19.4。我的MWE中主要且唯一的模型有两个DateTime:第一个和最后一个时刻。我的目的是通过提升日期(从过去到未来)和同时下降时间(从晚上到早上)对这些对象进行排序。因此,共享相同日期的事件应该是#34;反转"。谷歌告诉我cast是我想要使用的功能,但事实证明它没有达到预期的效果。相反,func.DATEfunc.TIME会向我提供我想要的结果。为什么呢?

#!/usr/bin/env python

import pprint

import sqlalchemy

from datetime import datetime, timedelta, timezone
from pathlib import Path

from sqlalchemy import cast, func, asc, desc
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session, relationship

from sqlalchemy import Column, ForeignKey
from sqlalchemy.types import DATE, TIME
from sqlalchemy.types import Integer, String, Date, Time, DateTime
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()


class MySlot(Base):

    __tablename__ = 'slot'

    id = Column(Integer, primary_key=True)

    fst = Column(DateTime)
    lst = Column(DateTime)

    def __repr__(self):
        return f'MySlot(id={self.id}, fst={self.fst}, lst={self.lst})'


if __name__ == '__main__':

    engine = create_engine(
        'sqlite:///{}'.format(
            Path(Path.cwd(), Path('sqlalchemy_poc.db'))
        )
    )
    SessionMaker = sessionmaker()
    SessionMaker.configure(bind=engine)

    session = SessionMaker()

    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)

    dt = datetime(year=2010, month=6, day=15, tzinfo=timezone.utc)

    fst0 = dt.replace(hour=5)
    lst0 = dt.replace(hour=6)

    fst1 = dt.replace(hour=19)
    lst1 = dt.replace(hour=20)

    slot0 = MySlot(fst=fst0, lst=lst0)
    slot1 = MySlot(fst=fst1, lst=lst1)

    session.add_all([slot0, slot1])

    query = session.query(MySlot).order_by(
        cast(MySlot.fst, DATE).asc(), cast(MySlot.fst, TIME).desc()
    )

    print(query)
    print(query.all())

    query = session.query(MySlot).order_by(
        func.DATE(MySlot.fst).asc(), func.TIME(MySlot.fst).desc()
    )

    print(query)
    print(query.all())

0 个答案:

没有答案