Column()获得了意外的关键字参数'primary_key'

时间:2019-10-17 15:34:28

标签: postgresql flask flask-sqlalchemy

我正在尝试对Flask进行小型应用。我从快速入门flask-sqlalchemy创建了User类。但是当我尝试运行该应用程序时,出现错误

代码:

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://test:test@localhost/test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Install(db.Model):
    id = db.Column(db.String, primary_key=True)
    date = db.Column(db.DateTime(), nullable=False)
    service = db.Column(db.String(120), nullable=False)
    theme = db.Column(db.String(120), nullable=False)
    plain = db.Column(db.String(120), nullable=False)
    responsible = db.Column(db.String(120), nullable=False)
    sender = db.Column(db.String(120), nullable=False)

    def __init__(self, id, date, service, theme, plain, responsible):
        self.id = id
        self.date = date
        self.service = service
        self.theme = theme
        self.plain = plain
        self.responsible = responsible
        self.sender = sender

    def __repr__(self):
        return f"|{self.id}|{self.date}|{self.service}|{self.theme}|{self.plain}|{self.responsible}|{self.sender}|"

和错误:

  File ".../src/app/Model.py", line 17, in <module>
    class User(db.Model):
  File ".../src/app/Model.py", line 18, in User
    id = db.Column(db.String, primary_key=True)
TypeError: Column() got an unexpected keyword argument 'primary_key'

1 个答案:

答案 0 :(得分:1)

您应该提供最大字符串长度:

尝试将id = db.Column(db.String, primary_key=True)替换为id = db.Column(db.String(50), primary_key=True)

此外,将id字段设置为具有自动增量的整数也是一种好习惯