繁体   English   中英

如何为 django model 中的每个部门创建唯一 ID

[英]how to create unique id for each department in django model

我在 django 中创建了一个 model 用于学生信息

<!-- 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 我应该怎么做

如果对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}"

这会将 append 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"

您现在可以将department_id用作 Django 管理员中的只读字段。

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

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

我建议首先有一个Department model,但如果你真的需要这个Student model。我会在你的 model 中添加一个额外的字段,然后在 model 保存时填充它。 这样你就可以确保唯一性并在任何 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参数强制唯一性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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