1👍
✅
You could make the code field a model field and generate the random code via its default property:
from django.utils.crypto import get_random_string
def set_code():
return get_random_string(length=6)
class Competition(models.Model):
...
#we use set_code as a callable as per the Field.default docs
code = models.CharField(max_length=6, default=set_code)
....
One caveat: Any existing records will all have the same code value after a migration, so you’d need to cycle through them and reset via set_code(). New records should be fine.
Source:stackexchange.com