Search code examples
pythonmysqlsqlalchemypyramid

Dropping constraint in SQLAlchemy


I created a class in Pyramid-SQLAlchemy and my models.py contained the following:

class Students(Base):

    __tablename__ = 'students'
    id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
    name = Column(String(50, convert_unicode=True), nullable=False, unique=True)  

I accidentally created the unique constraint and ran the initializedb.py command, and the schemas were created. I tried removing the unique constraint and rerunning the initializedb.py command but the Constraint wouldn't drop and I get this error.

sqlalchemy.exc.IntegrityError: (IntegrityError) column name is not unique u'INSERT INTO students (id,name) VALUES (?, ?)' (200,'Hailey')

How do I drop/modify this constraint?


Solution

  • The Pyramid initialize_*_db scripts call the MetaData.create_all, which is a very stupid function in that it is happy with any table with the same name if it exists. What this unfortunately means is that you need to drop the unique constraint by hand, or drop the entire database and create again.

    For any serious project I suggest you use the Alembic to handle database schema migrations.