开发者

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(mod开发者_运维问答els.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


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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜