M
M
max32772019-07-22 16:52:11
Django
max3277, 2019-07-22 16:52:11

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

2 answer(s)
S
Sergey Tikhonov, 2019-07-22
@tumbler

ref_code = models.CharField(default=lambda: get_random_string(32, chars), unique=True)

In general, what did uuid not please?

A
alternativshik, 2019-07-22
@alternativshik

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 question

Ask a Question

731 491 924 answers to any question