如何在Django模型中为每个部门创建唯一的id

2024-06-10 11:37:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我在django中创建了一个模型供学生参考

<!-- 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)

我希望为部门生成唯一的id,例如,如果我选择cse部门id应为cse0001、cse002,或者如果mech意味着id应为mech001、mech002,我该怎么办


Tags: django模型idmodelslanguagelength学生max
2条回答

我建议首先使用Department模型,但是如果您真的需要在Student模型上使用它的话。我会在模型中添加一个额外的字段,然后在模型保存时填充它。这样,您可以确保唯一性,并在任何ORM筛选或其他操作中使用它:


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)

现在,如果您试图创建一个具有现有department_id的学生,将抛出一个IntegrityError,因为我们可以使用department_id字段上的unique=True参数强制唯一性

如果department_id的要求是它是唯一的,那么可以使用Student主键。因此,除非您绝对需要存储在数据库中的department_id。我会在您从数据库中检索到学生实例后立即确定它

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}"

这将把Student主键附加到部门字符串

您可以像这样在模板中使用它

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

如果您需要在Django admin中显示它,您可以像这样添加到上面的department_id方法中

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

department_id.short_description = "Department ID"

现在,您可以在Django admin中使用department_id作为只读字段

最后,如果希望ID具有前导零,可以使用zfill()

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

相关问题 更多 >