如何在sqlalchemy中聚合距离

时间:2016-11-14 18:51:08

标签: python sqlalchemy postgis

我有以下查询

numbersDetail.realm != nil

如何聚合到属性的距离? e.g:

query = Studio.query.join(
        Location
    ).filter(
        func.ST_DWithin(Location.point, point, distance)
    ).order_by(
        func.ST_Distance(Location.point, point).label('distance')
    )

query[0].distance

1 个答案:

答案 0 :(得分:0)

最后,我使用生成器来注入属性

def smart_generator(query, column_name):
    for obj, additional_data in query.all():
        setattr(obj, column_name, additional_data)
        yield obj


distance_query = StudioLocation.point.ST_Distance(point).label('distance')
nearby_query = Location.point.ST_DWithin(point, distance)
studio_query = db.session.query(Studio, distance_query).join(Location)
studio_query = studio_query.filter(nearby_query).order_by('distance')
studio = smart_generator(studio_query, "distance")