[Answer]-Resave a models into a try catch

1πŸ‘

βœ…

As I undestand it you are getting an IntegrityError because your code has to be unique.
You could filter in the save method if an instance with the same code already exists:

def _generate_code(self):
    # have the whole code generation in one place
    return strftime('%y%m')+str(uuid4())[:4]

def save(self, *args, **kwargs):
    if self.pk is None:
        self.code = self._generate_code()
        while Organisation.objects.filter(code=self.code).exists():
            self.code = self._generate_code()
    super(Organisation, self).save(*args, **kwargs)

Maybe there are better ways to generate your code but don’t know why it must be a piece of a uuid4. You could also try a random string with the character set you need.

0πŸ‘

If you want to create a unique suffix then you can check if it exists and keep trying till you generate a non-existent code.

def save(self, *args, **kwargs):
    """ override save method to add specific values """
    if self.pk is None:
        for i in range(100):    # Try 100 times to avoid infinite loops 
            code = strftime('%y%m')+str(uuid4())[:4]
            if not Organisation.objects.filter(code=code):
                 break
        self.code = code
    super(Organisation, self).save(*args, **kwargs)
πŸ‘€arocks

Leave a comment