[英]SQLAlchemy filter_by query failing when float used
I have a model defined as follows: 我有一个定义如下的模型:
class EnergyProfiles(db.Model):
__tablename__ = "energy_profiles"
id = db.Column(db.Integer, primary_key=True)
device_id = db.Column(db.String(64), index=True, unique=False, nullable=False)
device_hardware = db.Column(db.String(64), index=True, unique=False, nullable=False)
location = db.Column(db.String(64), index=True, unique=False, nullable=False)
time = db.Column(db.String(64), index=True, unique=False, nullable=False)
accompanied = db.Column(db.Boolean)
wellbeing = db.Column(db.String(64), index=True, unique=False, nullable=False)
battery = db.Column(db.Integer, index=True, unique=False, nullable=False)
When I add new objects via an API I would like to check that the new object (the post_data
) does not already exist. 当我通过API添加新对象时,我想检查新对象(
post_data
)是否不存在。 This check was easy with 这张支票很容易
energy_profile_existing = EnergyProfiles.query.filter_by(**post_data).first()
After changing the battery
column type, however, from db.Integer
to db.ARRAY(db.Float())
the previous query.filter_by
fails with a postgres error (ignore the user
text below, it's docker compose output logs) 但是,将
battery
列类型从db.Integer
为db.ARRAY(db.Float())
,先前的query.filter_by
失败,并显示postgres错误(忽略下面的user
文本,它是docker组成输出日志)
operator does not exist: double precision[] = numeric[]
user_1 | LINE 3: WHERE energy_profiles.battery = ARRAY[0.1,20.1]
user_1 | ^
user_1 | HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
The post_data
contains battery
as part of the JSON object eg post_data
包含battery
作为JSON对象的一部分,例如
{
"device_id": "CP99",
"device_hardware": "Pycom",
"location": "irregular",
"time": "daytime",
"accompanied": false,
"wellbeing": "ok",
"battery": [0.11, 35.22]
}
As @benvc and @IljaEverilä pointed out when you pass an array without any explicit casting containing non-integer numeric constants, it is assumed that they are of type numeric
. 正如@benvc和@IljaEverilä指出的那样,当您传递不包含任何非整数数字常量的显式转换的数组时,假定它们的类型为
numeric
。
What you can do is cast the array's contents to float
and to do that you can use the array([])
literal to declare the array and cast()
it to ARRAY(Float)
using the datatype: 你可以做的是投了数组的内容 ,以
float
要做到这一点,你可以使用array([])
字面声明数组和cast()
它以ARRAY(Float)
使用的数据类型:
{
"device_id": "CP99",
"device_hardware": "Pycom",
"location": "irregular",
"time": "daytime",
"accompanied": false,
"wellbeing": "ok",
"battery": cast(array([0.11, 35.22]), ARRAY(Float))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.