flask-migrate doesn't work When I add models with ForeignKey

匿名 (未验证) 提交于 2019-12-03 08:33:39

问题:

class User(db.Model):     __tablename__ = 'user'     id = db.Column(db.Integer, primary_key=True)     email = db.Column(db.String(64), unique=True)     # 是不是应该加密下,不能明文存储?应该设置多长的空间? 14.7.18 4:22 by lee     password = db.Column(db.String(100))     nickname = db.Column(db.String(64))     school = db.Column(db.String(20))     sex = db.Column(db.String(5))     status = db.Column(db.String(10))     grade = db.Column(db.String(18)) 

I have a database remains. Then I add model to models.py:

class PubSquare(db.Model):     id = db.Column(db.Integer, primary_key=True)      author_id = db.Column(db.Integer, db.ForeignKey('user.id'))     author = db.relationship('User', backref=db.backref('publish'))      subject = db.Column(db.String(100))     timestamp = db.Column(db.DateTime, default=datetime.datetime.now) 

Then I run migrate script, it call bug:

NoReferencedTableError: Foreign key associated with column 'pub_square.author_id' could not find table 'user' with which to generate a foreign key to target column 'id'

Befor this time, I can run migrate script successfully for serveral times.But this time, when it refer to foreignkey relationship, it doesn't work.

to prove my models code is right, I re-create the database, it works. So, it's the flask-migrate calls to this bug.

回答1:

@knight We have migrated for many times.'user' table is in the database. But I found that if I code like

author_id = db.Column(db.Integer) 

and migrate, It's nothing wrong. And than add the code like

author_id = db.Column(db.Integer, db.ForeignKey('user.id')) 

and migrate again, It passed. It's strange. I don't know why exactly.

Our migrate code is

api.update_db_from_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, db.metadata) 


回答2:

From what I can see the user table is not being created (could not find table 'user' with which to generate a foreign key to target column 'id'). Try migrating the User first and, therefore, making the user table, and then doing the PubSquare.

EDIT: Have you tried reading the docs? http://sqlalchemy-migrate.readthedocs.org/en/v0.7.1/changeset.html#constraint seems to help.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!