Django foreignkey,检索值

时间:2016-10-24 08:24:08

标签: django

我正在尝试从ForeignKey获取值,但它会抛出类型错误。请给我一个解决方案。

class LenderInvestment(models.Model):
    user = models.ForeignKey(User)
    investment = models.DecimalField(max_digits=15, decimal_places=2, default=1000000)
    initial_capital = models.DecimalField(max_digits=12, decimal_places=2, **optional)
    date_stamp = models.DateField(default=datetime.date.today)

def __unicode__(self):
    return str(self.initial_capital)


class LoanDisbursement(models.Model):
    user = models.ForeignKey(User)
    initial_capital = models.ForeignKey(LenderInvestment, **optional)
    loan_applicant = models.ForeignKey(LoanApplication)
    money_disbursed = models.DecimalField(max_digits=10, decimal_places=2)
    pay_slip = models.FileField(_('Upload depostited payslip'), upload_to=upload_location2,
                            storage=FileSystemStorage(location=settings.PROTECTED_ROOT))
    date_stamp = models.DateField(default=datetime.date.today)

    def __unicode__(self):
        return str(self.user)

def loan_disbursement_receiver(sender, instance, *args, **kwargs):
    initial_capital = instance.initial_capital[0]
    money_disbursed = instance.money_disbursed
    initial_capital -= Decimal(money_disbursed)
    instance.initial_capital = initial_capital

pre_save.connect(loan_disbursement_receiver, sender=LoanDisbursement)

该错误表示不允许索引;我怎样才能获得initial_capital的第一个索引值?提前谢谢。

1 个答案:

答案 0 :(得分:0)

您的pre_save已连接到LoanDisbursement模型,该模型具有LenderInvestment模型的外键。问题是外键字段只能有一个值 - 指向LenderInvestment模型对象的链接。所以。而不是

initial_capital = instance.initial_capital[0]

尝试做

initial_capital = instance.initial_capital

因为它是获取连接对象的唯一正确方法。