在自定义方法上使用 Hybrid_property 使用 Sqlalchemy 表达式

use*_*820 5 python mysql sqlite sqlalchemy python-2.7

我希望创建一个查询,扫描表并根据一些 calc_dist(attribute) 函数计算表中给定位置和存储的地理位置属性之间的差异,该函数可以动态过滤它并返回从最近到的切片结果最远

假设表类是这样的:

Hoo(Base):
    attribute_names = Column(......)

    @hybrid_property
    def calc_dist(self):
        #do some foo(self.attr_) 
Run Code Online (Sandbox Code Playgroud)

如何做类似的事情:

session.query(Hoo).filter(Hoo.attr_ and given_geo_loc USING this location value- Is there a way to pass this val into calc_dist here?)
Run Code Online (Sandbox Code Playgroud)

每次传入具有新给定地理位置的新请求时,我们如何使用此给定位置将其传递到过滤器查询中,以便 calc_dist 计算它?

对于每个给定的位置参数,都会有一个切片查询结果,该结果根据从最近到最远的限制生成值。

更新

真的很有帮助

我尝试像这样使用它来解决我的问题:

class Hoo(Base):
    #Table info
    __tablename__ = 'hoo'
    #mappers
    lat = Column(String(50))
    lng = Column(String(50))

    @hybrid_method
    def rankByloc(self, lat, lng):
        return haversine((float(self.lat), float(self.lng)), (float(lat), float(lng)))

    @rankByloc.expression
    def rankByloc(cls, lat, lng):
        return haversine((float(self.lat), float(self.lng)), (float(lat), float(lng)))
Run Code Online (Sandbox Code Playgroud)

当我做

session.query(Hoo).order_by(Hoo.rankByloc(lat, lng))
Run Code Online (Sandbox Code Playgroud)

给出错误:

NameError: global name 'self' is not defined
Run Code Online (Sandbox Code Playgroud)

当我将其更改为@hybrid_property时

它说

TypeError: rankByloc() takes exactly 3 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)

更新#2

好的,我正在使用混合方法。但是表达式描述符中的 python 函数不起作用。即这需要改变:

 @rankByloc.expression
        def rankByloc(cls, lat, lng):
            return haversine((float(self.lat), float(self.lng)), (float(lat), float(lng)))
Run Code Online (Sandbox Code Playgroud)

更新#3

所以我正在研究这个并弄清楚如何使用来自供应商独立的 Sqlalchemy 的等效存储过程并从 orderby 调用 hasrsine 函数。

除了 SQLA 类的类属性上的逻辑运算符之外,是否可以使用外部函数调用?我的意思是我想对值而不是 sql 对象操作函数。