Any way to speed up case-insensitive Django UniqueConstraint?

The Django docs show this example UniqueConstraint:

UniqueConstraint(Lower('name').desc(), 'category', name='unique_lower_name_category')

First off, the desc() produces errors in the admin interface. (Edited version below.)

ProgrammingError at /admin1/app/tablename/add/
syntax error at or near "DESC"
LINE 1: ...lename" WHERE LOWER("tablename"."name") DESC = (LO...
                                                             ^
Request Method: POST
Request URL:    http://host/admin/app/tablename/add/?_changelist_filters=a_val
Django Version: 4.1.5
Exception Type: ProgrammingError
Exception Value:    
syntax error at or near "DESC"
LINE 1: ...lename" WHERE LOWER("tablename"."name") DESC = (LO...

Okay, never mind that. Let's drop desc(). And, I don't have two fields, I only have one. So look at this UniqueConstraint:

UniqueConstraint(Lower('name'), 'name', name='unique_lower_name')

When I load data into that table in Postgres (13 or 14, say), it's quite slow.

Is there an easy way to speed up having a constraint that says "Only one version of this name (ignoring case) should be in the table"?

I could drop the constraint.

I could also add a field that's all lowercase and put a unique constraint on that field. It would be extra DB info (a cache), but for performance sake.

Back to Top