Hi
I want to create an unique id in django charfield field:
Its better to make a sort of custom Charfiled like this:
class AutoGenerateCodeField(models.CharField):
def __init__(self, min_length=None, *args, **kwargs):
self.min_length = min_length or 4
super(AutoGenerateCodeField, self).__init__(*args, **kwargs)
def pre_save(self, model_instance, add):
if add:
attr_name = self.attname
unique_id = get_random_string(self.min_length)
look_up = {attr_name: unique_id}
count = 0
while self.model.objects.filter(**look_up).exists():
count += 1
unique_id = '{unique_id}-{count}'.format(unique_id=unique_id,
count=count)
look_up[attr_name] = unique_id
setattr(model_instance, attr_name, unique_id)
return unique_id
return super(AutoGenerateCodeField, self).pre_save(model_instance, add)
or to override the save() method on the model field and catch the
IntegrityError?
like this PSEUDO code:
def save(self, *args, **kwargs):
if not self.pk:
if not self.unique_id:
retries = 5
while retries > 0:
self.unique_id = get_random_string(4)
try:
with transaction.atomic():
super().save(*args, **kwargs)
except IntegrityError:
retries -= 1
else:
break
super().save(*args, **kwargs)
which is more efficient, django style?
Thanks for your helps
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/35b579e9-5fd8-49f8-85bd-046be511e160%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.