简体   繁体   中英

Table not migrating - Flask-SQLAlchemy

I have the following line of code in my models.py file:

referalls = db.table('referrals',
                 db.Column('referrer', db.String(64), db.ForeignKey('User.email')),
                 db.Column('referral', db.String(64), db.ForeignKey('User.email'))
                 )

This is to create a many-to-many relationship table for a referral system I'm trying to implement.

However, when I run my migrate/upgrade command, Alembic is not creating the table.

I'm following the official Flask-SQLAlchemy tutorial: http://flask-sqlalchemy.pocoo.org/2.1/models/

For clarity's sake, here's the User class:

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    password_hash = db.Column(db.String(128))
    confirmed = db.Column(db.Boolean, default=False)
    name = db.Column(db.String(64))
    location = db.Column(db.String(64))
    about_me = db.Column(db.Text())
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
    ...

I believe my problem might be the following line (pulled from the official Flask-SQLAlchemy documentation):

tags = db.relationship('Tag', secondary=tags,
       backref=db.backref('pages', lazy='dynamic'))

I tried:

referalls = db.relationship('User', secondary=referalls,
                            backref=db.backref('users', lazy='dynamic'))

But same thing: Alembic's not identifying the referrals table.

Any input on this is greatly appreciated.

I had the same problem and solved by using a class inheriting db.Model instead of declaring a table the way the flask tutorial suggests. When I defined everything as a class it just worked. Possibly its a problem with alembic.

Try:

class Referalls(db.Model):
    __tablename__ = 'referalls'
    referrer = db.Column(db.String(64), db.ForeignKey('User.email'))
    referral = db.Column(db.String(64), db.ForeignKey('User.email'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM