2016-05-27 32 views
0

这里是什么,我试图做一个简单的用例:如何编写与需要查询的混合方法的模型参数

class Location(db.Model): 
    __tablename__ = 'locations' 

    id = db.Column(db.Integer, primary_key=True) 
    name = db.Column(db.UnicodeText, nullable=False) 

    # a postgres EARTH type 
    earth_location = db.deferred(db.Column(EARTH)) 

    @hybrid_method 
    def location_distance_from_current_location(self, current_latitude, current_longitude): 
     return db.func.earth_distance(
      db.func.ll_to_earth(
       current_latitude, current_longitude), self.earth_location) 

我知道如何写这个SQL,但是怎么办我在SQLAlchemy中对此进行建模?

SELECT 
    locations.id, locations.name, 
    earth_distance(ll_to_earth(40.766810, -73.978227), locations.earth_location) AS location_distance_from_current_location 
FROM 
    locations 
WHERE (earth_box(ll_to_earth(40.766810, -73.978227, 10000) @> locations.earth_location) 
ORDER BY location_distance_from_current_location ASC 

我如何获得在混合方法通过current_latitudecurrent_longitude值?我不需要使用混合方法作为filter,因为这是由earth_box()函数照顾我的。

谢谢!

回答

0

混合方法是一种同时具有Python实现和SQL实现的方法。您提供了SQL实现,但不提供Python实现。你最好的办法就是提供Python实现。

如果您不需要在每个实例访问location_distance_from_current_location,你可以当你查询获取值:

​​

这给你的(Location, distance)元组的列表。

+0

感谢您澄清混合方法。实际上,混合方法可能是这项工作的错误工具。我不需要Python实现。我只需要正确的SQL来执行并返回'distance_from_current_location'作为位置对象的一部分。 – lostdorje

+0

@lostdorje问题是,你想要的不是真的可能,正是因为它需要输入经纬度。你可以做的最好的做法是从'Location'对象中单独查询它。 – univerio

相关问题