I am writing a RESTful api using Flask and Flask-SQLalchemy, as well as Flask-Login. I have a model Users
that's initialized like:
class Users(UserMixin, db.Model):
__tablename__ = "users"
# STATIC Standard required info
id = db.Column("id", db.Integer, primary_key = True)
public_id = db.Column("public_id", db.String(50), unique = True)
email = db.Column("email", db.String(50), unique = True)
username = db.Column("username", db.String(20), unique = True)
password = db.Column("password", db.String(20))
# DYNAMIC Standard required info
lat = db.Column("lat", db.Float)
lon = db.Column("lon", db.Float)
There are other elements in the table but the lat and lon are most relevant. I have a method distanceMath()
that takes in the currently logged in user's latitude and longitude, as well as a latitude and longitude from the table to calculate distance between them. But I can't figure out how to access the table values during the following query that calls distanceMath
without receiving a syntax error:
lat1 = current_user.lat
lon1 = current_user.lon
users = Users.query.filter(distanceMath(lat1, Users.lat, lon1, Users.lon)==1)
output = []
for user in users:
data = {}
data["username"] = user.username
output.append(data)
return str(output)
Just in case, here's the distanceMath
method:
# Haversine Distance
def distanceMath(lat1, lat2, lon1, lon2):
distance = math.acos(math.sin(math.radians(lat1))*math.sin(math.radians(lat2))) + math.cos(math.radians(lat1))*math.cos(math.radians(lat2))*math.cos(math.radians(lon1)-math.radians(lon2))
return distance
An example of the error is:
TypeError: must be real number, not InstrumentedAttribute
Which, in my understanding, is essentially saying that User.lat
and User.lon
don't refer to a float or even a number, and instead an attribute to a table. My question is how to actually use what lat and lon are equal to (In the database they are equal to 37.7 and -122.4 respectively).
See Question&Answers more detail:
os