Check if a generated code is already in the DB, and generate a new one if it is
Add unique constraint/index to the DB
Possibly replace the empty string with None when there is no code yet (that way you can use unique=True instead of requiring an unique index w/ a WHERE criterion to ignore empty strings)
unique=True
instead of requiring an unique index w/ a WHERE criterion to ignore empty strings)