Answer the question
In order to leave comments, you need to log in
How to make a random entry value in a Django model?
I have a user model where
chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
code = get_random_string(32, chars)
...
ref_code = models.CharField(default=code, unique=True)
Since users already exist, a
django.db.utils.IntegrityError occurs : (1062, "Duplicate entry '4krrtv4eacbn0lw6sii88gkedqm7xn45' for key 'ref_code'")
It's understandable, it tries to give all users the same "random" string.
How to avoid this on an already existing user model?
Answer the question
In order to leave comments, you need to log in
ref_code = models.CharField(default=lambda: get_random_string(32, chars), unique=True)
remove uniq and default, make null=True, do migration to create field, then do datamigration to populate all fields randomly, then add uniq and default and do migration again
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question