繁体   English   中英

ForeignKey 的 NOT NULL 约束失败(null=True)

[英]NOT NULL constraint failed for ForeignKey(null=True)

我有两个模型,即ApplicantLoanRequest 每当创建Applicant实例时,都会向进行 API 调用的函数发送信号。 来自调用的数据以及发送信号的实例的主键被保存为LoanRequest

但是,当我保存LoanRequest时,它会出现以下错误:

django.db.utils.IntegrityError: NOT NULL constraint failed: queues_loanrequest.dealer_id_id

这是我的代码:

class Applicant(models.Model):
    app_id = models.CharField(max_length=100)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.CharField(max_length=100)
    date_posted = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.first_name + " " + self.last_name


class LoanRequest(models.Model):
    loan_request_id = models.CharField(max_length=100)
    app_id = models.ForeignKey(Applicant, on_delete=models.CASCADE)
    FICO_score = models.CharField(max_length=100)
    income_risk_score = models.CharField(max_length=100)
    DTI = models.CharField(max_length=100)
    date_requested = models.DateTimeField(default=timezone.now)
    loan_request_status = models.CharField(max_length=100,blank=True)
    dealer_id = models.ForeignKey(Dealer, on_delete=models.CASCADE,blank=True)

def credit_check(sender, instance, **kwargs):
    credit_json = get_credit(instance.pk) #credit information for applicant
    credit_json = json.loads(credit_json)
    new_request = LoanRequest.objects.create(app_id=instance, FICO_score=credit_json["ficco-score"],
                                income_risk_score=credit_json["income-risk-score"],
                               DTI=credit_json["DTI"])


对 Django 非常陌生,非常感谢帮助!

LoanRequest有一个字段

dealer_id = models.ForeignKey(Dealer, on_delete=models.CASCADE,blank=True)

由于dealer_id没有null=True ,因此在不提供dealer_id情况下创建LoanRequest实例将引发您遇到的数据库错误。

您需要在LoanRequest的实例化中提供一个dealer_id ,它应该是一个Dealer实例,或者更改您的LoanRequest模型,以便dealer_id字段为null=True

请参阅上面的评论:在 Django 模型外键上使用后缀_id - 这样做几乎总是不正确的。

在没有null=True blank=True情况下指定blank=True对 ForeignKey 不是很有用。

改用这个:

dealer_id = models.ForeignKey(Dealer, on_delete=models.CASCADE, blank=True, null=True) 

这将使该字段可选。 否则,每次创建LoanRequest时都必须指定Dealer

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM