Django custom ID field with if condition

Viewed 88

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

  1. N-G-20120700001

  2. N-G-20120700002

  3. 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

  1. N-F-20120700001

  2. N-F-20120700002

  3. 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...

1 Answers

Here is one possible solution based on your. It is fairly simple so I think you don't need an explanation.

def save(self, *args, **kwargs):
    prefix = 'N-{}-{}'.format(self.goal[0].upper(),
                              date.today().strftime("%y%m%d"))
    today_instances = self.__class__.objects.filter(membership_num__icontains=prefix).count()

    self.membership_num = prefix + '{0:04d}'.format(today_instances + 1)
    super(Athlete, self).save(*args, *kwargs)

Not tested but you can try with the following

from django.core.exceptions import ObjectDoesNotExist

#........

def save(self, *args, **kwargs):
    prefix = 'N-{}-{}'.format(self.goal[0].upper(),
                              date.today().strftime("%y%m%d"))
    today_instances = 0
    try:
        last_record = self.__class__.objects.filter(membership_num__icontains=prefix).last()

        today_instances = int(last_record.membership_num[-4:])
    except ObjectDoesNotExist:
        pass
    
    self.membership_num = prefix + '{0:04d}'.format(today_instances + 1)
    super(Athlete, self).save(*args, *kwargs)
Related