2

My flask app works absolutely well locally. I am deploying the app to Python Anywhere. The problem is that when I run flask db upgrade in the pythonanywhere bash I get the error below (when I do any db migration and upgrade locally there are no errors):

sqlalchemy.exc.IntegrityError: (_mysql_exceptions.IntegrityError) 
(1215, 'Cannot add foreign key constraint') [SQL: '\nCREATE TABLE 
comments (
\n\tid INTEGER NOT NULL AUTO_INCREMENT, \n\tbody TEXT, \n\ttimestamp 
DATETIME, \n\tdisable BOOL, \n\tauthor_id INTEGER, \n\tpost_id 
INTEGER, \
n\tPRIMARY KEY (id), \n\tFOREIGN KEY(author_id) REFERENCES users 
(id), \n\tFOREIGN KEY(post_id) REFERENCES posts (id), \n\tCHECK 
(disable IN (
0, 1))\n)\n\n']

I have checked other similar questions and known the possible sources of this error but I don't see any of the problems mentioned. Here is the comments model:

class Comment(db.Model):
    __tablename__ = 'comments'
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text)
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    disable = db.Column(db.Boolean)
    author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))
Eric O.
  • 474
  • 4
  • 23
  • 1
    Having the definition of the `users` and `posts` table would help, but anyway, have you checked if the datatype for the FK columns matches the referenced columns? Do you already have data inside, so that the order of creation would matter? – Cynical Jan 07 '19 at 11:37
  • 1
    An explanation would be that your `CREATE TABLE comments` statement is executed before the `CREATE TABLE posts` and/or `CREATE TABLE users` . – Thomas G Jan 07 '19 at 11:38
  • @Cynical locally I have data but online not yet, it's when am doing the first deployment. And yes I have checked that the datatype matches. In fact, that is why the app works perfectly well locally. – Eric O. Jan 07 '19 at 11:46
  • @Thomas G if so, what is the way forward? – Eric O. Jan 07 '19 at 11:46
  • perhaps remove the class Comment and create the class Post and class User first? Or perhaps you needed to do a flask db init/flask db migrate before you do the upgrade – conrad Jan 15 '19 at 12:41
  • Did you fix this ? I have the same error, I checked the types, the order, the connection and I still receiving the error –  Feb 13 '19 at 16:40

0 Answers0