I'm writing API using Flask, Flask-RESTful, Flask-SQLAlchemy and MySQL. The problem is that filter() and filter_by don't work at all.
Model:
from app import db
from datetime import datetime
class AreaModel(db.Model):
__tablename__ = 'aqi_records'
id = db.Column(
db.Integer,
primary_key=True
)
aqi = db.Column(
db.Integer,
index=False,
unique=False,
nullable=False
)
latitude = db.Column(
db.Float,
index=False,
unique=False,
nullable=False
)
longitude = db.Column(
db.Float,
index=False,
unique=False,
nullable=False
)
created = db.Column(
db.DateTime,
index=False,
unique=False,
nullable=False,
default=datetime.now()
)
def __repr__(self):
return '<Area {}>'.format(self._string_coords())
def _string_coords(self):
return str(self.latitude) + '-' + str(self.longitude)
def as_dict(self):
r = {c.name: getattr(self, c.name) for c in self.__table__.columns}
r['created'] = str(r['created'])
return r
Resource:
from flask_restful import Resource, request
from models import AreaModel
class AreaResource(Resource):
def get(self):
area_coords = request.args.get('area_coords')
if not '-' in area_coords:
return {'code': 400, 'message': 'Invalid coordinate format'}, 400
latitude, longitude = area_coords.split('-')
latitude, longitude = float(latitude), float(longitude)
area = AreaModel.query.filter_by(latitude=latitude).first() # this is the line with the problem
if not area:
return {'code': 404, 'message': 'Area not found'}, 404
return area.as_dict()
When I use AreaModel.query.all() I get all records in table. But if I add filter I always get None as a result and I can't understand why
Edit 1: received data (coords) is correct; type: float
Edit 2:
.get() isn't working too
[1.5, 1.33, 1.625, 1.11, 1.34567]and only 1.5 and 1.625 were found.