4👍
✅
Just test the existence of the generated code in the loop.
from django.contrib.auth.models import User
def unique_rand():
while True:
code = password = User.objects.make_random_password(length=8)
if not Person.objects.filter(code=code).exists():
return code
class Person(models.Model):
code = models.CharField(max_length=8, unique=True, default=unique_rand)
Note that there is no round brackets in the default=unique_rand
argument.
If you want to limit the number of attempts then change the loop from while
to for
:
def unique_rand():
for _ in range(5):
...
raise ValueError('Too many attempts to generate the code')
Source:stackexchange.com