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)
class History(models.Model):
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()
def __str__(self):
return self.name
我只想在name
之后将值employee_ID
和Leave
从模型History
存储到模型status == 1
中。我对django还是很陌生,请帮助我。
答案 0 :(得分:1)
如果您想将一个模型与另一个模型相关联,则可以根据关系使用OneToOneField
,ManyToManyField
,ForeignKey
等
您要做的是,您有一个模型Leave
,其中包含字段employee_ID
,name
和user
另一个模型History
,具有字段employee_ID
,name
,user
(从Leave继承)和emp_ID
,full_name
。这只是扩展该模型类并创建新的模型对象。两者将仅无关。 (我没有足够的经验来告诉您确切的/详细的行为)
因此,根据您的情况,您可以从历史记录模型中获取一个OneToOneField
(或其他基于您的业务逻辑的东西)来保留类似这样的模型。
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)
class History(models.Model):
emp_ID = models.CharField(('employee ID'),max_length = 25)
full_name = models.CharField(('Name'),max_length = 40)
leave = models.OneToOneField(Leave, on_delete = models.SET_NULL)
然后您可以按以下方式保存数据:
# I am assuming you're inside some view and you want to create leave for the user who is logged in, refactor based on your requirements
leave = Leave.objects.create(employee_ID="EMPLOYEEID", name="EMPLOYEENAME", user=request.user)
# here pass the leave that we have created previously
history = History.objects.create(emp_ID="EMPLOYEEID", full_name="EMPLOYEEFULLNAME", leave=leave)
我假设您还有休假开始datetime
字段。我认为您还应该研究为什么两个模型都重复使用员工ID。
如果您有任何疑问/疑问,请告诉我。谢谢〜