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


i using django 1.8.6 python 2.7.8. trying save model called project field "jobnumber", combination of current year plus 4 character string of model's next id. example: year 2016, next id of model 1, make 4 char string , 0001, add year , char field value should "20160001".

here model:

@python_2_unicode_compatible  # if need support python 2 class project(models.model):     name = models.charfield(max_length=50)     jobnumber = models.charfield(max_length=8)     contractor = models.foreignkey(contractor, on_delete=models.cascade, default=101)     created_by = models.foreignkey(user, related_name='project_created_by')     created_date = models.datetimefield()     modified_by = models.foreignkey(user, related_name='project_modified_by')     modified_date = models.datetimefield()     def __str__(self):         return self.name     def save(self, *args, **kwargs):         if not self.id:             self.created_date = timezone.now()         self.modified_date = timezone.now()         super(project, self).save(*args, **kwargs) 

any appreciated!

you can't next id until save, because allocated database on insert. there no alternative 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 should using auto_now_add , auto_now created_date , modified_date respectively, remove need set them in save method.


Comments