Search code examples
pythonpostgresqlsqlalchemypsycopg2

SQLAlchemy @hybrid_method and @distance.expression TypeError: float() argument must be a string or a number, not 'InstrumentedAttribute'


I got this model and this hybrid method and expression:

def gc_distance(lat1, lon1, latitude, longitude, math=math):
    import pdb; pdb.set_trace()
    dst = (3958.75 *
           math.acos(math.sin(float(lat1) / 57.2959) * math.sin(float(latitude) / 57.2960) +
                     math.cos(float(lat1) / 57.2958) * math.cos(float(latitude) / 57.2958) *
                     math.cos(longitude / 57.2958 - float(lon1)/57.2958)))
    return dst


class Job(db.Model):

    __tablename__ = "job"

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80), nullable=False)
    city = db.Column(db.String(250), nullable=False)
    state = db.Column(db.String(10), nullable=False)
    zipCode = db.Column(db.String(10), nullable=False)
    latitude = db.Column(db.String(10), nullable=False)
    longitude = db.Column(db.String(10), nullable=False)
    description = db.Column(db.String(200), nullable=False)
    narrative = db.Column(db.String(250), nullable=False)
    companyLogo = db.Column(db.String(250), nullable=False)
    companyName = db.Column(db.String(250), nullable=False)
    companyURL = db.Column(db.String(100), nullable=False)
    time_created = db.Column(db.DateTime, nullable=False)

    @hybrid_method
    def distance(self, lat, lng):
        import pdb; pdb.set_trace()
        return gc_distance(lat, lng, self.latitude, self.longitude)

    @distance.expression
    def distance(cls, lat, lng):
        import pdb; pdb.set_trace()
        return gc_distance(lat, lng, cls.latitude, cls.longitude, math=func)

I'm making this call to my methods:

@classmethod
def getJobsWithinXMiles(cls, lat1: str, lon1: str, dst: str,
                            page: int, per_page: int)-> "JobModel":

             stmt = db.session.query(
                        Job,
                        Job.distance(lat1, lon1).
                        label('distance')).\
                    subquery()


              job_alias = aliased(Job, stmt)

              jobs = db.session.query(job_alias).\
                    filter(stmt.c.distance < dst).\
                    order_by(stmt.c.distance).\
                    paginate(page, per_page).\
                    params(lat1=float(lat1),
                           lon1=float(lon1),
                           dst=int(dst),
                           page=int(page),
                           per_page=int(per_page)
                           )
                return jobs

Now when I call this method from my view I got this error :

line 27, in gc_distance dst = (3958.75 * TypeError: float() argument must be a string or a number, not 'InstrumentedAttribute'

The error is in the function gc_distance(lat1, lon1, latitude, longitude, math=math). I see that latitude is of type 'InstrumentedAttribute' and that is what is generating the error

Could someone help in finding the reason of this error?


Solution

  • The function gc_distance() tries to convert latitude to a float, though it is also used as the column element parameter in the SQL expression. You should move the conversions to the respective hybrids:

    @hybrid_method
    def distance(self, lat, lng):
        return gc_distance(lat, lng, float(self.latitude), float(self.longitude))
    
    @distance.expression
    def distance(cls, lat, lng):
        return gc_distance(lat, lng, cls.latitude.cast(db.Float), cls.longitude.cast(db.Float), math=func)
    

    and then instead of float(latitude) just use latitude. The long term solution would be to fix the data type of the columns latitude and longitude to a suitable numeric type.