I am new to django. What I am currently trying to do is set a value which is a primary key and non-editable automatically generated depending upon the values entered in the same model to some other fields. Here is an example:
class Student(models.Model):
student_id = models.CharField(max_length=100, primary_key=true)
name = models.CharField(max_length=100)
class = models.CharField(max_length=200)
roll_no = models.CharField(max_length=500)
So, what I am trying to achieve is if someone enters following information:
name = Haris
class = 8th
roll_no = 104011
The automatically generated primary key that would be non-editable for field "student_id" would be:
student_id = Haris_8th_104011
Does anyone have an idea how to achieve this? Hope my example made the query clear though.
You can do this way overriding save method. Note that class variable clashesh with original builtin class name please migrate once as i changed the variable name
class Student(models.Model):
student_id = models.CharField(max_length=100, primary_key=True, editable=False)
name = models.CharField(max_length=100)
classes = models.CharField(max_length=200)
roll_no = models.CharField(max_length=500)
def save(self, *args, **kwargs):
self.student_id = f'{self.name}_{self.classes}_{self.roll_no}'
super(Student,self).save(*args, **kwargs)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.