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.
π€Bernhard Vallant
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
- [Answer]-Django-tastypie how to assign default value in id
- [Answer]-A model with a defined field throws an AttributeError when accessing it
- [Answer]-Using Django rest framework as a rest client
- [Answer]-Django save method overwritten and type object 'cursos' has no attribute 'object'
Source:stackexchange.com