我一直在为我的应用程序的模型进行一段时间的摔跤。每当我似乎“修理”一件事,另一件事就会破裂。从谷歌搜索和搜索在这里我终于来到这里,然而,它现在抛出另一个错误,我无法弄清楚为什么。
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.db'
db = SQLAlchemy(app)
class Students(db.Model):
__tablename__ = 'Students'
id = db.Column(db.Integer, primary_key=True, unique=True)
first_name = db.Column(db.String(20), primary_key=False, unique=True)
last_name = db.Column(db.String(20), primary_key=False, unique=True)
image = db.Column(db.String(20), primary_key=False, unique=True)
def __init__(self, id, first_name, last_name, image):
self.id = id
self.first_name = first_name
self.last_name = last_name
self.image = image
def __repr__(self):
return '<Student: {} {}>'.format(self.first_name, self.last_name)
@app.route('/')
def index():
s = Students.query.all()
return render_template('index.html', Students=s)
if __name__ == '__main__':
app.run(debug=True)
在模型中,您会在所有字段上看到unique
和primary_key
因为没有它我会收到以下错误:
Column() missing 1 required positional argument: 'unique'
或
Column() missing 1 required positional argument: 'primary_key'
现在我在这里读到某个地方,因为我继承了Models,我不应该包含__tablename__
,但没有它我会收到这个错误:
sqlalchemy.exc.InvalidRequestError: Class <class '__main__.Students'> does not have a __table__ or __tablename__ specified and does not inherit from an existing table-mapped class.
毕竟我终于归结为这个错误,我假设是因为它说没有主键?:
sqlalchemy.exc.ArgumentError: Mapper Mapper|Students|Students could not assemble any primary key columns for mapped table 'Students'
我做错了什么?