简体   繁体   中英

how to create unique id for each department in django model

i created a model in django for student information

<!-- language: python -->
class student(models.Model):
    department_choices=(('cse','cse'),('mech','mech'),('EEE','EE'))
    name=models.CharField(max_length=35)
    department=models.CharField(max_length=30,choices=department_choices)

i want id to be generated unique for department for example if i chose cse department id should be cse0001, cse002 or if mech means id should be mech001, mech002 what should i do

If the requirement for department_id is that it is simply unique you can use the Student primary key. So unless you absoutely need the department_id stored in the database. I would determine it on the fly after you have retrieved the student instance from the database.

class Student(models.Model):
    DEPARTMENT_CHOICES=(('cse','cse'),('mech','mech'),('EEE','EE'))   

    name=models.CharField(max_length=35)
    department=models.CharField(max_length=30,choices=DEPARTMENT_CHOICES)

    def department_id(self):
        return f"{self.department}{self.id}"

This will append the Student primary key to the department string.

You can use it in your templates like this.

<ul class="student">
  <li>Name: {{ a_student.name }}</li>
  <li>Dep ID: {{ a_student.department_id }}</li>
</ul>

If you need to display this in the Django admin you can add to the above department_id method like this.

def department_id(self):
    return f"{self.department}{self.id}"

department_id.short_description = "Department ID"

You can now use department_id as a read only field in the Django admin.

Lastly, if you want the ID to have leading zeros you can use zfill() .

def department_id(self):
    return f"{self.department}{str(self.id).zfill(4)}"

I'd recommend having a Department model firstly, but if you really need this on the Student model. I'd add an extra field to your model, then populate it when the model saves. That way you can ensure uniqueness and use it in any ORM filtering or other operations:


class Student(models.Model):
    department_choices = (('cse', 'cse'), ('mech', 'mech'), ('EEE', 'EE'))
    name = models.CharField(max_length=35)
    department = models.CharField(max_length=30, choices=department_choices)
    department_id = models.CharField(max_length=20, unique=True)

    def save(self, *args, **kwargs):
        # check here for PK, PK will only be populated if save()
        # has already been called before, so this means the
        # department_id field will only be set when the model is created
        # remove this condition if you want it regenerated after every save() call.
        if not self.pk:
            self.department_id = f"{self.department}{self.pk}"

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

Now, an IntegrityError will be thrown if you try to create a student which has an existing department_id as we can enforce uniqueness with the unique=True argument on the department_id field.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM