[英]Auto increment the filed in Python Django model
This is my model这是我的 model
class Department(BaseModel):
name = models.CharField(max_length=20, null=False)
maximum_number_of_employees = models.PositiveIntegerField(MinValueValidator(0), MaxValueValidator(3))
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=False)
def __str__(self):
return self.name
I want to auto-increment the maximum_number_of_employees field upon the creation of the department and the associate of the employee to each department so that I can validate that the maximum_number_of_employees do not exceed the max limit我想在创建部门时自动增加 maximum_number_of_employees 字段以及员工与每个部门的关联,以便我可以验证 maximum_number_of_employees 不超过最大限制
Override save method like this:像这样覆盖保存方法:
class Department(BaseModel):
name = models.CharField(max_length=20, null=False)
maximum_number_of_employees = models.PositiveIntegerField(MinValueValidator(0), MaxValueValidator(3))
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=False)
def save(self, *args, **kwargs):
if Department.objects.select_related('employee').count() < MAX_LIMIT:
self.maximum_number_of_employees += 1
super(Department).save(self, *args, **kwargs)
else:
raise ValueError("Limit exceeded!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.