簡體   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