I am going to set the custom id with the name of "membership_num" with the increment number by 1, in every new register athlete with a prefix for each record like:
if the "goal field in model" is "gym" it should generate the ID:
description: N-Gym-Year Month Day then the number
N-G-20120700001
N-G-20120700002
N-G-20120700003
if the "goal field in model" is "fitness" it should generate the ID:
description: N-Fitness-Year Month Day then the number
N-F-20120700001
N-F-20120700002
N-F-20120700003
Models.py
class Athlete(models.Model):
first_name = models.CharField(max_length=50)
membership_num = models.CharField(max_length=255, blank=True, editable=False)
goal = models.CharField(max_length=10, choices=[('gym', 'Gym'), ('fitness', 'Fitness')])
I found and tried the following solution in StackOverflow but it does not generate the correct ID...
def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
if not self.membership_num:
prefix = 'N{}'.format(timezone.now().strftime('%y%m%d'))
prev_instances = self.__class__.objects.filter(membership_num__icontains=prefix)
if prev_instances.exists():
last_instance_id = prev_instances.last().membership_num[-4:]
self.membership_num = prefix + '{0:04d}'.format(int(last_instance_id) + 1)
else:
self.membership_num = prefix + '{0:04d}'.format(1)
super(Athlete, self).save(*args, *kwargs)
please help me...