使用子查询对SQLAlchemy(flask-sqlalchemy)进行SQL查询

时间:2019-02-28 17:21:01

标签: python postgresql sqlalchemy flask-sqlalchemy

我有此SQL查询,我想转换为SLQAlchemy(flask-sqlalchemy) 查询使用分页

SQL查询

queryPostgres = db.text("""
    SELECT *, COUNT(*) OVER () as RowCount
    FROM (
        SELECT * ,
            ( 3958.75 *
            acos(sin(:lat1 / 57.2958) * sin( cast(latitude as double precision) / 57.2958) +
                 cos(:lat1 / 57.2958) * cos( cast(latitude as double precision) / 57.2958) *
                 cos( cast(longitude as double precision) / 57.2958 - :lon1/57.2958)))
            as distanceInMiles
        FROM "job" ) zc
    WHERE zc.distanceInMiles < :dst
    ORDER BY zc.distanceInMiles
    LIMIT :per_page
    OFFSET :offset
""") 

的身份发送到SQLALchemy
 @classmethod
    def getJobsWithinXMiles2(cls, lat1: str, lon1: str, dst: str):

        return cls.query.filter(
            (3958.75 *
                acos(sin(lat1 / 57.2958) * sin(latitude / 57.2958) +
                cos(lat1 / 57.2958) * cos(latitude / 57.2958) *
                cos(longitude / 57.2958 - lon1/57.2958))) as distanceInMiles)  \
            .where(distanceInMiles < dst) \
            .order_by(distanceInMiles) \
            .paginate(page=_page, per_page=_per_page)

但是我在SQLAlchemy中遇到错误

这是澄清方式

class Job(db.Model):

    __tablename__ = "job"

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80), nullable=False)
    city = db.Column(db.String(250), nullable=False)
    state = db.Column(db.String(10), nullable=False)
    zipCode = db.Column(db.String(10), nullable=False)
    latitude = db.Column(db.String(10), nullable=False)
    longitude = db.Column(db.String(10), nullable=False)
    description = db.Column(db.String(200), nullable=False)
    narrative = db.Column(db.String(250), nullable=False)
    companyLogo = db.Column(db.String(250), nullable=False)
    companyName = db.Column(db.String(250), nullable=False)
    companyURL = db.Column(db.String(100), nullable=False)
    time_created = db.Column(db.DateTime, nullable=False)

但我无法使其正常运行。 有人可以帮忙将此SQL查询转换为SQLAlchemy吗?

1 个答案:

答案 0 :(得分:0)

此问题的解决方案在这里:

Convert a complex SQL query to SQLAlchemy

谁正确回答了?恩,那个救了我一次以上的人Ilja Everilä

非常感谢Ilja的帮助和支持