Search code examples
postgresqlsqlalchemyunique-constraintunique-index

Create unique index with SQLAlchemy on Postgres using MD5


I have a column that can contain a long text, that I want to create a unique index on.

I read on several places (for example here) that the way to do it is to create an index on the MD5 of the column.

I tried adding the following code:

__table_args__ = (
        sa.Index('unique_data_hash', 'MD5(data)', unique=True)
    )

but when I try to use it I get

KeyError: 'MD5(data)'

How can I add such index using SQLAlchemy?


Solution

  • After another search I realised the answer is to use sa.func.md5, which worked like a charm!