postgresql 无法通过Flask SQLAlchemy插入新记录

p8ekf7hl  于 2022-12-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(222)

当我尝试通过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)

这是我在models文件中定义“海滩”类的代码。

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

这是我创建类的示例并尝试插入到数据库中的代码。

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
);

有一个s imilar-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列上。谢谢您的建议!

vwkv1x7d

vwkv1x7d1#

如果有人遇到类似的问题...
解决方案是从参数列表中删除“id”,从海滩类中删除self.id = id位,并在创建Beach类的新示例时删除“id”。
我猜想,由于beaches表被配置为在添加新记录时自动递增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

当创建新示例并将其添加到数据库时,它应该如下所示...

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()

相关问题