当我尝试通过flask sqlalchemy向表中插入一个新行时,我收到以下错误。我只在尝试插入新行时看到此错误。我可以毫无问题地查询现有行。
ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'builtin_function_or_method' [SQL: 'INSERT INTO beaches (id, beach_name, lat, long, beach_description) VALUES (%(id)s, %(beach_name)s, %(lat)s, %(long)s, %(beach_description)s)'] [parameters: {'lat': 45.01, 'beach_description': 'some stuff here', 'id': <built-in function id>, 'long': 45.01, 'beach_name': 'test'}] (Background on this error at: http://sqlalche.me/e/f405)
这是我在模型文件中定义“beach”类的代码。
class Beach(db.Model):
__tablename__ = 'beaches'
id = db.Column(db.Integer, primary_key=True)
beach_name = db.Column(db.String(256))
lat = db.Column(db.Numeric)
long = db.Column(db.Numeric)
beach_description = db.Column(db.String(256))
def __init__(self, id, beach_name, lat, long, beach_description):
self.id = id
self.beach_name = beach_name
self.lat = lat
self.long = long
self.beach_description = beach_description
这是我创建类的实例并尝试插入db的代码。
beach_name = "test"
lat = 45.01
long = 45.01
beach_description = "some stuff here"
new_beach = Beach(id, beach_name, lat, long, beach_description)
db.session.add(new_beach)
db.session.commit()
这是我要插入的表的架构。我正在使用Postgres。
CREATE TABLE beaches (
id SERIAL PRIMARY KEY,
beach_name text,
lat double precision,
long double precision,
beach_description text
);
有一个similar-looking post,评论者建议在创建类的实例时删除“id”。对我来说,看起来像下面的代码。我尝试过这种变化,但我得到了同样的错误。
beach_name = "test"
lat = 45.01
long = 45.01
beach_description = "some stuff here"
new_beach = Beach(beach_name, lat, long, beach_description)
db.session.add(new_beach)
db.session.commit()
即使上面的建议不起作用,我建议问题是在我的表中使用自动递增id列的某个地方。谢谢你的建议!
如果有人遇到类似的问题......
解决方案是从参数列表中删除'id',从Beach类中删除self.id = id
位,并在创建Beach类的新实例时删除'id'。
我想由于海滩表配置为在添加新记录时自动增加id(通过串行数据类型),因此在创建类的新实例时不必提供id。
该类的修订代码如下所示。
class Beach(db.Model):
__tablename__ = 'beaches'
id = db.Column(db.Integer, primary_key=True)
beach_name = db.Column(db.String(256))
lat = db.Column(db.Numeric)
long = db.Column(db.Numeric)
beach_description = db.Column(db.String(256))
def __init__(self, beach_name, lat, long, beach_description):
self.beach_name = beach_name
self.lat = lat
self.long = long
self.beach_description = beach_description
在创建新实例并将其添加到db时,它应该看起来像这样......
beach_name = "test"
lat = 45.01
long = 45.01
beach_description = "some stuff here"
new_beach = Beach(beach_name, lat, long, beach_description)
db.session.add(new_beach)
db.session.commit()