无法通过Flask SQLAlchemy

时间:2019-04-27 22:09:19

标签: postgresql python-2.7 flask-sqlalchemy

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

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

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列会自动增加。感谢您的任何建议!

1 个答案:

答案 0 :(得分:0)

如果有人遇到类似问题...

解决方案是从参数列表中删除“ id”,并从Beach类中删除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()