我有一个提交数据的表单,但在提交到数据库之前,它将从外部获取值。
这是我的models.py
class Employee(models.Model):
nik = models.CharField(max_length=100)
name = models.CharField(max_length=100)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("system:detail",kwargs={'pk':self.pk})
class EmpLoan(models.Model):
status = models.BooleanField()
nominal = models.DecimalField(max_digits=10, decimal_places=0)
emp = models.ForeignKey(Employee, related_name='emploan')
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.emp.name
class EmpInstallment(models.Model):
nominal = models.DecimalField(max_digits=10, decimal_places=0)
loan = models.ForeignKey(EmpLoan, related_name='empinstallment')
created_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.loan.emp.name
view.py
class EmployeeCreateView(CreateView):
fields = ()
model = models.Employee
def form_valid(self, form):
self.object = form.save(commit=False)
data = self.object.EmpLoan.EmpInstallment.object.get(id=1)
self.object.nik = data
self.object.save()
return super(ModelFormMixin, self).form_valid(form)
如何访问EmpInstallment
上的数据?...
我正在尝试使用此data = self.object.EmpLoan.EmpInstallment.object.get(id=1)
但它不起作用。
依然是django的学习者和非常棒的人
答案 0 :(得分:0)
EmpInstallment - > ForeignKey to ---> EmpLoan -----> ForeignKey to --- Employee
class EmployeeCreateView(CreateView):
fields = ()
model = models.Employee
def form_valid(self, form):
employee_instance = form.save(commit=False)
# try to get the emploan instance
emploan = employee_instance.emploan.first()
if emploan:
empinstallment = emploan.empinstallment.first()
if empinstallment:
pass # there you can execute your codes
# there you have access to empinstallment