2

我正在使用 Flask-migrate 创建迁移。我有2个模型如下 -

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)
    password_hash = db.Column(db.String(120))
    handle = db.Column(db.String(120))
    type_user = db.Column(db.String(50))
    display_pic = db.Column(db.String(100))

    def __init__(self, handle, email, raw_password):
        self.handle = handle
        self.email = email
        # Save the hashed password
        self.set_password(raw_password)

    def __repr__(self):
        return '<User %r>' % self.username

    def set_password(self, raw_password):
        self.password_hash = generate_password_hash(raw_password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)


class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    likes = db.Column(db.Integer)
    user = db.relationship('User', backref=db.backref('posts'))
    body = db.column(db.Text)

第一个模型,即用户是在第一次迁移中创建的,这很好。但是当我添加第二个模型(Post)时,忽略了外键约束,并生成了以下迁移文件-

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('post',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('likes', sa.Integer(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    ### end Alembic commands ###


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('post')
    ### end Alembic commands ###

它只是忽略了用户和正文字段。我该如何解决这个问题,以便使用所有字段?

4

1 回答 1

2

对不起。我的错,我对外键的文档感到困惑。以下代码完美运行 -

from backend import db
from werkzeug.security import generate_password_hash, check_password_hash


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)
    password_hash = db.Column(db.String(120))
    handle = db.Column(db.String(120))
    type_user = db.Column(db.String(50))
    display_pic = db.Column(db.String(100))
    posts = db.relationship('Post', backref='user', lazy='dynamic')

    def __init__(self, handle, email, raw_password):
        self.handle = handle
        self.email = email
        # Save the hashed password
        self.set_password(raw_password)

    def __repr__(self):
        return '<User %r>' % self.username

    def set_password(self, raw_password):
        self.password_hash = generate_password_hash(raw_password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)


class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    likes = db.Column(db.Integer)
    body = db.Column(db.Text)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
于 2015-12-26T11:03:29.440 回答