0

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?

0

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your response. I also discovered that there is a max key length of 767 bytes so String(256) will not fit. I was able to decrease the length and everything works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.