I created two models "Category" and "Item". There is a field "title" in category model, I want the value of the "title field" to be prefix of my "unique id field" in Item module can anyone suggest me a solution for this problem.
Thank you
The default id
in django models is something like this:
class Custom(models.Model):
id = models.IntegerField(primary_key=True, editable=False)
So, the possible way to achieve the requirement is to change the IntegerField
to CharField
.
Technically you can use "String PK Field" But, you should be aware of the problems/performance issues if you are going to use that. more: Strings as Primary Keys in SQL Database
If you still really wish to migrate to String PKs:
First you need to use the CharField
instead of IntegerField
and override the save()
method of model
from django.db.models import Max
class Item(models.Model):
id = models.CharField(primary_key=True, editable=False)
prefix = models.CharField(max_length=100)
def save(self, **kwargs):
if not self.id:
max = Item.objects.aggregate(id_max=Max('id'))['id_max']
self.id = "{}{:05d}".format(self.prefix, max if max is not None else 1)
super().save(*kwargs)
According to this: Django generate custom ID