在使用Sqlalchemy表达式的自定义方法上使用混合_属性

2024-09-30 20:30:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望创建一个查询,它扫描一个表,并根据某个calc_dist(attribute)函数计算表中给定位置和存储的地理位置属性之间的差异,该函数在移动时对其进行过滤并返回结果(从最近到最远)

假设table类类似于:

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

    @hybrid_property
    def calc_dist(self):
        #do some foo(self.attr_) 

如何执行以下操作:

^{pr2}$

每次有新的给定地理位置的新请求出现时,我们如何使用这个给定的位置将其传递到过滤器查询中,以便calc_dist计算这个值?在

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

更新

This真的很有帮助

我试着用它来解决我的问题:

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)))

当我这么做的时候

session.query(Hoo).order_by(Hoo.rankByloc(lat, lng))

给出错误:

NameError: global name 'self' is not defined

当我把它改成@hybrid_property时

上面写着

TypeError: rankByloc() takes exactly 3 arguments (1 given)

更新2

好的,我用混合法。 但是表达式描述符中的python函数不起作用。i、 e.这需要改变:

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

更新3

因此,我正在研究this,并找出如何使用独立于供应商的Sqlalchemy中的存储过程的等价物并从orderby调用haversine函数。在

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


Tags: 函数selfreturndistdefcalcattributecolumn