When I try to reinitialize my database, I keep getting an IntegrityError:
sqlalchemy.exc.IntegrityError: (IntegrityError) (1217, 'Cannot delete or update a parent row: a foreign key constraint fails') '\nDROP TABLE users' ()
In my init_db script, I have:
def main(argv=sys.argv):
if len(argv) != 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = create_engine('...')
Session.configure(bind=engine)
session = Session()
Base.metadata.bind=engine
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
It would let me drop the Users table, which is:
class User(Base):
__tablename__='users'
__table_args__={
'mysql_engine':'InnoDB',
'mysql_charset':'utf8',
}
user_id = Column(Integer, primary_key=True, unique=True)
username = Column(VARCHAR(16), primary_key=True, unique=True)
name = Column(VARCHAR(16))
password = Column(VARCHAR(20))
email = Column(VARCHAR(30))
creation = Column(DateTime, default = datetime.datetime.now)
def __init__(self, un, name, pw, email):
self.username = un
self.name = name
self.email = email
self.password = pw
I see two possible reasons:
ForeignKey to the users table, but which is not mapped to any sqlalchemy model and therefore is not dropped during drop_all operation.sqlalchemy model. For example, the addresses table on the DB has a ForeignKey which points to the users table, but your model Address (or to put it properly, the mapper for the Address) does not configure this ForeignKey, and therefore during drop_all sqlalchemy has no way of knowing that this table should be dropped before the referenced one (users).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With