![](/img/trans.png)
[英]is there any way to create unique id's to particular field in django model
[英]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.