MarkAWard
MarkAWard

Reputation: 1919

SQLAlchemy + MYSQL unique string column gets truncated

I would like to enforce the uniqueness of a column, but after I add an object to the database the string in this unique column gets cutoff. I have a model defined as follows:

class Topic(Base):
    __tablename__ = 'topic'
    id = Column(Integer(), primary_key=True)
    slug = Column(String(256), nullable=False, unique=True)
    name = Column(String(256))

Im using SQLAlchemy and MYSQL. When I inspect the table that gets created:

mysql> DESCRIBE topic;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| slug     | varchar(10)  | NO   | UNI | NULL    |                |
| name     | varchar(256) | YES  |     | NULL    |                |

How do I get the slug column to have type varchar(256) and Key UNI?

Upvotes: 0

Views: 1455

Answers (1)

Haleemur Ali
Haleemur Ali

Reputation: 28313

SQLAlchemy doesn't support database migrations. For that, you'd need something like Alembic, which is authored by the same person who wrote SQLAlchemy.

Alternatively, you can issue a DDL statement directly on the MySQL server, and change the Table Definition in Python.

[on mysql]

ALTER TABLE topic MODIFY COLUMN slug VARCHAR(256);

[on python]

class Topic(Base):
    __tablename__ = 'topic'
    id = Column(Integer(), primary_key=True)
    slug = Column(String(256), nullable=False, unique=True)
    name = Column(String(256))

Upvotes: 1

Related Questions