Search code examples
sqlitepeewee

How to add a unique insensitive constraint on a peewee model?


I would like to add a unique insensitive constraint to the following model using peewee orm with a sqlite database

import peewee as p

db = p.SqliteDatabase(':memory:')

class Player(p.Model):
   name = p.CharField()
  
   class Meta:
      database = db

I would like to prevent adding 'joe' and 'Joe' as player name in the table. As the field is case sensitive, a unique constraint is not enough.

Thank you for your ideas !


Solution

  • You can specify arbitrary constraints in the Meta.constraints list:

    from peewee import *
    
    db = SqliteDatabase(':memory:')
    
    class K(Model):
        key = TextField()
        class Meta:
            constraints = [SQL('UNIQUE ("key" COLLATE NOCASE)')]
            database = db
    
    db.create_tables([K])
    
    K.create(key='k1')
    K.create(key='K1') # Fails