[Answered ]-How to combine the current year with the next Model Id and save it in a field

2👍

You can’t get the next id until you save, because it is allocated by the database on insert. So there is really no alternative but to save twice.

def save(self, *args, **kwargs):
    if not self.id:
        super(Project, self).save(*args, **kwargs)
        year = datetime.datetime.now().year
        self.jobNumber = '{}{:04d}'.format(year, self.id)
    super(Project, self).save(*args, **kwargs)

Note that you should be using auto_now_add and auto_now for created_date and modified_date respectively, which would remove the need to set them yourself in the save method.

Leave a comment