Create an Unique Charfiled

13 views
Skip to first unread message

Aprimus

unread,
Dec 13, 2018, 5:04:17 PM12/13/18
to Django users
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
Reply all
Reply to author
Forward
0 new messages