Django automatically generates unique model fields and recursively invokes an auto-generator, if not unique

I am working on a Django project where Thing will have a unique 10-digit key, in addition to the standard automatically incrementing ID integer fields. A simple random number function is used to create it. [I'm sure there is a better way to do this, too]

When a Thing is created, a 10-digit key is created. I use .validate_unique () to verify the key is unique. If this is not the only one, is there an easy way, can I recursively call the key generator (makeKey ()) before 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}) 

thanks

+2
source share
1 answer

There is no need for recursion here - the 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() 
+7
source

Source: https://habr.com/ru/post/975819/


All Articles