Python 烧瓶SQLAlchemy过滤器和don#x27过滤器;不能使用浮点值
我正在使用Flask、Flask RESTful、Flask SQLAlchemy和MySQL编写API。问题是Python 烧瓶SQLAlchemy过滤器和don#x27过滤器;不能使用浮点值,python,mysql,sqlalchemy,Python,Mysql,Sqlalchemy,我正在使用Flask、Flask RESTful、Flask SQLAlchemy和MySQL编写API。问题是filter()和filter\u by根本不起作用 型号: from app import db from datetime import datetime class AreaModel(db.Model): __tablename__ = 'aqi_records' id = db.Column( db.Integer, pri
filter()
和filter\u by
根本不起作用
型号:
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
当我使用AreaModel.query.all()
时,我得到表中的所有记录。但如果我添加过滤器,结果总是得到None
,我不明白为什么
编辑1:
接收到的数据(coords)正确;
类型:浮子
编辑2:
.get()
不起作用浮点数很难使用,因为浮点数的文字表示可能与计算中使用的值或存储在数据库中的值不完全对应。此行为在对的回答中进行了深入讨论。可以在MySQL中找到并找到使用浮点进行查询的特定实例
为了解决这个问题,MySQL建议使用DECIMAL
类型代替FLOAT
或DOUBLE
在这个特殊的例子中,我认为您可以选择使用DECIMAL
(和Python类型)或字符串来表示纬度和经度
- 如果您打算使用这些值执行数值计算,
可能是更好的选择DECIMAL
- 如果只查询精确的值,可以使用将值存储为字符串
将sqlalchemy作为sa导入
从sqlalchemy.ext.declarative导入声明性基础
从sqlalchemy导入orm
Base=声明性_Base()
类别测试(基本):
__tablename_uu='floattest'
id=sa.Column(sa.Integer,主键=True)
横向=sa.列(sa.浮动)
定义报告(自我):
返回f'{self.\uuuuuu class.\uuuuuu name.\uuuuu}(lat={self.lat})'
引擎=sa。创建引擎('mysql:///test,echo=True)
Base.metadata.drop_all(bind=engine,checkfirst=True)
Base.metadata.create_all(bind=engine)
Session=orm.sessionmaker(bind=engine)
浮动=[1.5,1.33,1.625,1.11,1.34567]
会话=会话()
对于浮点数中的v:
会话添加(浮动测试(lat=v))
session.commit()
对于浮点数中的v:
res=session.query(FloatTest).filter(FloatTest.lat==v).first()
打印(v,res)
打印()
session.close()
输出(删除SQL日志):
1.5浮动测试(lat=1.5)
1.33无
1.625浮动试验(lat=1.625)
1.11无
1.34567无
我认为最好存储lat/long作为字符串-浮点值在查询过程中可能无法可靠地往返。我尝试使用[1.5,1.33,1.625,1.11,1.34567]
进行快速测试,只找到了1.5和1.625。有关详细信息,请参见和example@snakecharmerb成功了!非常感谢你!另请参见@snakecharmerb您是否介意将您的答案作为答案(而不是评论)发布,以便我将其标记为最佳解决方案?
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()