问题描述
我正在一个Django项目中,除了标准的自动递增ID整数字段之外,Thing还将具有唯一的10位数字键.我使用一个简单的随机数函数来创建它. [我相信也有更好的方法可以做到这一点]
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]
创建事物后,将创建一个10位数字的密钥.我使用.validate_unique()检查密钥的唯一性.如果它不是唯一的,是否有一种简单的方法可以递归调用Key生成器(makeKey()),直到它通过?代码如下:
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:
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})
谢谢
推荐答案
此处无需递归-基本的while循环可以解决问题.
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()
这篇关于Django,自动生成唯一的模型字段,如果不是唯一的,则递归调用自动生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!