我如何通过整数列来划分sqlalchemy中的时差?

时间:2016-07-28 21:10:26

标签: python sqlalchemy

我正在尝试通过以下方式编写和算法来命令链接:链接点数/时间差(秒)/行数

我遇到麻烦的唯一部分是时差部分。

(Link.query
     .join(Point, (Point.link == Link.id))
     .group_by(Link.id)
     .filter(Link.visibility == 1)
     .order_by(((Link.points / (datetime.now() - Link.time).seconds) / func.count(Point.id)).desc()))

1 个答案:

答案 0 :(得分:1)

注意:嗯,你没有提供任何你的ORM样本,所以我猜到了。

我认为你不需要将python日期类型与sql日期类型混淆。您需要使用数据库中的函数。

如果使用SQLite,您可以使用此顺序:

# only valid for sqlite
my_order = func.count(Link.points)/(functions.current_timestamp() - Link.time) / func.count(Point.id)

如果使用MySQL,您可以使用此订单:

# only valid for MySQL
my_order = func.count(Link.points)/func.time_to_sec(func.timediff(functions.current_timestamp(), Link.time)) / func.count(Point.id)

以下是使用SQLite的完整示例:

#!/usr/bin/python
import datetime

from sqlalchemy import create_engine, Column, types, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session, Session, relationship, backref
from sqlalchemy.schema import DefaultGenerator
from sqlalchemy.sql import functions, func

Base = declarative_base()

class Link(Base):
    __tablename__ = "link"
    id = Column(types.Integer, primary_key=True)
    visibility = Column(types.Integer, default=1)
    time = Column(types.DateTime, default=functions.current_timestamp())

    points = relationship("Point", backref="link")

    def __repr__(self):
        return "Link(id=%r, visibility=%r, time=%r, points=[#%r])" % (self.id,
                                self.visibility, self.time, len(self.points))

class Point(Base):
    __tablename__ = "point"
    id = Column(types.Integer, primary_key=True)
    link_id = Column(types.Integer, ForeignKey('link.id'))

    def __repr__(self):
        return "Point(id=%r, link_id=%r" % (self.id, self.link_id)


engine = create_engine('sqlite:///:memory:', echo=True)
session = scoped_session(sessionmaker(bind=engine))
Base.metadata.create_all(engine)

for i in range(10):
    time = datetime.datetime(2016, 1, 31 - i)
    link = Link(time=time)
    for j in range(15 - i):
        link.points.append(Point())
    session.add(link)

my_order = (func.count(Link.points)
            / (functions.current_timestamp() - Link.time)
            / func.count(Point.id))


session.query(Link).join(Point).filter(Link.visibility==1)\
.group_by(Link.id).order_by(my_order.desc()).all()

可以编写一个根据SQL数据库编译的通用函数,为此,请参阅here