Creating a student from applicant model

Question:

How to create a student from my applicants models? and also giving the students a custom registration number that will be incrementing as new students register.

This my Applicant model

enter image description here

Asked By: MAHMUD UMAR

||

Answers:

class Student(models.Model):
    ....
    registration_number = models.IntegerField()

    def save(*args, **kwargs):
        if self.registration_number is None:
            last_student = Student.objects.order_by("-registration_number").first()
            if last_student is None:
                self.registration_number = 0
            else:
                self.registration_number = last_student.registration_number + 1

        super().save(*args, **kwargs)

Something like the following should handle the a prefix

prefix = "something"
qs = Student.objects.annotate(increment=Cast(SubStr("registration_number", len(prefix) + 1), output_field=models.IntegerField()))
last_student = Student.objects.order_by("-increment").first()
if last_student is None:
    self.registration_number = f"{prefix}0"
else:
    self.registration_number = f"{prefix}{last_student.increment + 1}
Answered By: Alombaros
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.