flask-migrate doesn't work When I add models w

2019-04-17 23:34发布

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.

2条回答
ら.Afraid
2楼-- · 2019-04-17 23:49

@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)
查看更多
神经病院院长
3楼-- · 2019-04-17 23:55

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.

查看更多
登录 后发表回答