I'm using the def_save func to format but obviously it's wrong because it increments based on the id.
class Category(models.Model):
categories = models.CharField(max_length=100)
shortterm = models.CharField(max_length=20, null=True, blank=True)
class Requestor(models.Model):
id = models.AutoField(primary_key=True)
date_filed = models.DateTimeField(auto_now_add=True, null=True,
verbose_name='date_filed')
category = models.ForeignKey(Category, on_delete=models.CASCADE,
null=True, verbose_name="Category")
**reference_code = models.CharField(max_length=500, verbose_name=(
'Reference'), default='Auto Assign', blank=True)**
def save(self):
date_ref = timezone.localtime(self.date_filed)
if self.reference_scholarship == 'Auto Assign':
last_id = Requestor.objects.latest('id')
curr_id = last_id.pk
new_id = int(curr_id) + 1
# self.ticketcode = self.tickettype.ShortTerm + '-' + str(new_id).zfill(4)
self.reference_scholarship = str(self.category.shortterm) + '-' +date_ref.strftime('%m%d%Y') + '-' +str(new_id).zfill(2)
super(Requestor, self).save()
else:
super(Requestor, self).save()
The result for the reference code should be like this.
id |
date_filed |
category |
reference_code |
1 |
01012021 |
local |
lsp-01012021-1 |
2 |
01012021 |
foreign |
fsp-01012021-1 |
3 |
01012021 |
local |
lsp-01012021-2 |
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…