Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, auto generating unique model fields and recursively calling auto generator if not unique

I am working on a Django project where a Thing would have a unique 10 digit Key, in addition to the standard auto incrementing ID integerfield. I use a simple random number function to create it. [I'm sure there's a better way to do this too]

When a Thing is created, a 10 digit Key is created. I use the .validate_unique() to check the Key's uniqueness. If its not unique, is there a simple way I can recursively call the Key generator (makeKey()) until it passes? Code follows:

Models.py:

class Thing(models.Model):
    name=models.CharField(max_length=50)
    key=models.IntegerField(unique=True)

Views.py:

def makeKey():
    key=''
    while len(key)<10:
        n=random.randint(0,9)
        key+=`n`
    k=int(key)
    #k=1234567890   #for testing uniqueness
    return k

def createThing(request):
    if ( request.method == 'POST' ):
    f = ThingForm(request.POST)
try:
    f.is_valid()
    newF=f.save(commit=False)
    newF.key=makeKey()
    newF.validate_unique(exclude=None)
    newF.save()
    return HttpResponseRedirect(redirect)

except Exception, error:
    print "Failed in register", error
    else:
        f = ThingForm()
    return render_to_response('thing_form.html', {'f': f})

Thank you

like image 333
rich Avatar asked Jan 21 '23 07:01

rich


1 Answers

No need for recursion here - a basic while loop will do the trick.

newF = f.save() 
while True:
    key = make_key() 
    if not Thing.objects.filter(key=key).exists():
        break
newF.key = key
newF.save()
like image 63
Daniel Roseman Avatar answered Apr 25 '23 17:04

Daniel Roseman