这是我的第一个模特
from django.db import models
from django.contrib.auth.models import User
CHOICES = (('Earned Leave','Earned Leave'),('Casual Leave','Casual Leave'),('Sick Leave','Sick Leave'),('Paid Leave','Paid Leave'))
STATUS_CHOICES = (('0', 'Rejected'),('1', 'Accepted'),)
class Leave(models.Model):
employee_ID = models.CharField(max_length = 20)
name = models.CharField(max_length = 50)
user = models.ForeignKey(User, on_delete = models.CASCADE, null =True)
type_of_leave = models.CharField(max_length = 15, choices = CHOICES)
from_date = models.DateField()
to_date = models.DateField()
status = models.CharField(max_length = 15, choices = STATUS_CHOICES)
@property
def date_diff(self):
return (self.to_date - self.from_date).days
这是我的第二个模特
class History(models.Model):
first_name = models.CharField(max_length = 50)
last_name = models.CharField(max_length = 50)
employee_ID = models.CharField(max_length = 20)
earned_leave = models.IntegerField()
casual_leave = models.IntegerField()
sick_leave = models.IntegerField()
paid_leave =models.IntegerField()
在保存第一个模型Leave
之后,我写了重写
def save(self, *args, **kwargs):
super(Leave, self).save()
if self.employee_ID == History.employee_ID:
if self.status == '1':
if self.type_of_leave == 'Earned Leave':
history = History.objects.update(
earned_leave = self.date_diff,
)
但是在保存第一个模型后,“历史记录”模型中的所有条目都将更新。每个用户在历史记录表中都有一个单独的条目,其中包含用户的详细信息(first_name, last_name, employee_ID
),其余用户的默认值为10
。保存Leave
模型后,仅应与employee_ID
模型中与Leave
模型的History
关联的条目进行更新。为此,我给出为if self.employee_ID == History.employee_ID:
,但它不起作用。
我甚至尝试过-
def save(self, *args, **kwargs):
super(Leave, self).save()
if self.employee_ID == History.employee_ID:
if self.status == '1':
if self.type_of_leave == 'Earned Leave':
history = History.objects.update(
earned_leave = History.earned_leave - self.date_diff,
)
但这不起作用,什么也没有更新,并且出现错误unsupported operand types
因此,该项目的基础是员工离职管理。当用户申请请假并被接受时,剩余天数应在“历史记录”表或模型中得到更新。
如果有其他方法,请共享。
答案 0 :(得分:0)
History.objects.update(...)
实际上确实更新了所有History
对象。您应该在查询中指定要更新的内容:
from django.db.models import F
def save(self, *args, **kwargs):
super(Leave, self).save()
if self.status == '1':
if self.type_of_leave == 'Earned Leave':
history = History.objects.filter(employee_id=self.employee_id).update(
earned_leave = F('earned_leave') - self.date_diff,
)
此处的F()
表达式是指列的值,将由数据库而不是Python计算。