How to I create a CharField with peewee which is unique if not null?

Viewed 152

I would like to create a Model with peewee where a Charfield is either null or a unique value. For example, I would think that it could be done with constraints, Meta, or perhaps both, but trying to do so is giving me a headache.

Does anyone have a solution for this in peewee?

1 Answers

The answer, as with most things in peewee, is pretty simple. Adding unique=True and null=True looks to work well.

class myModel(db.Model):
    id = PrimaryKeyField()
    myCharField = CharField(max_length=6, unique=True, null=True)
Related