5

I am looking to create a query that scans through a Table and calculates a difference between a given location and stored Geo location attribute in a Table based on some calc_dist(attribute) function that filters it on the go and returns results in slices from nearest to farthest

lets say the table class is something like:

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

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

How to do something like :

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

Everytime a new Request with new Given Geo Location comes in, how would we pass this using this Given location into the filter query so that the calc_dist calculates this?

For each given location argument, there would be a sliced query result that yields value based on this limit from nearest to farthest.

UPDATE

This was really helpful

I tried using it like this for my problem:

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

When I do

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

Gives Error:

NameError: global name 'self' is not defined

When I change it to @hybrid_property

It says

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

Update #2

Ok I am using hybrid_method. But a python function inside expression descriptor doesn't work. i.e. this needs to change:

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

UPDATE #3

So I am looking at this and figuring out how to use an Equivalent of Stored Procedures from vendor independent Sqlalchemy and call the haversine function from orderby.

Is it possible to use external Function calls besides logical operators over Class attributes of SQLA Classes? I mean I want to operate functions on values not on sql objects.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user2290820
  • 2,709
  • 5
  • 34
  • 62

0 Answers0