title: Django, auto generating unique model fields and recursively calling auto generator if not unique
body: <p>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]</p>
  
  <p>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:</p>
  
  <p>Models.py:</p>
  
  <pre><code>class Thing(models.Model):
      name=models.CharField(max_length=50)
      key=models.IntegerField(unique=True)
  </code></pre>
  
  <p>Views.py:</p>
  
  <pre><code>def makeKey():
      key=''
      while len(key)&lt;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})
  </code></pre>
  
  <p>Thank you</p>