Is there any way to check if a value exists in a model when assigning it as a default value? If the assigning value exists (it's not unique), then generate another value. (Read comments):
def unique_rand():
return ... # Generate a random string with 8 characters length
# It shouldn't exists among other persons
# If exists then generate another random string
class Person(models.Model):
code = models.CharField(max_length=8, unique=True, default=unique_rand())
Maybe the workaround cannot be inside unique_rand
but somewhere inside Person
class.
I don't want override save
method because I need the code
before save
. Also, I don't want to use uuid
randoms.