使用flask我碰到的问题
When scattering Flask Models, RuntimeError: ‘application not registered on db’ was raised
有问题代码
app = Flask(__name__)
db.init_app(db)
def test():
db.create_all()
修改为
def test():
with app.app_context():
db.create_all()
Class does not have a table or tablename specified and does not inherit from an existing table-mapped class
Per the Flask-SQLAlchemy docs inheriting from db.Model will automatically setup the table name for you.
The reason you are seeing this message is because you don’t have a primary key defined for that table. The error message is kind of unhelpful, but adding a primary key will fix this problem.
flask-sqlalchemy-多对一, 一对多关系
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
addresses = db.relationship('Address', backref='person',
lazy='dynamic')
class Address(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(50))
person_id = db.Column(db.Integer, db.ForeignKey('person.id'))
当我生成一个 address对象, address 存在一个 persion属性,这个属性名是如何来的? 答案 persion.id 的 persion来的.
参考
when-scattering-flask-models-runtimeerror-application-not-registered-on-db-w