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

时间:2020-01-23 06:09:21

标签: python django database model foreign-keys

我有两个模型,分别是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的新手,将非常感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

LoanRequest有一个字段

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

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

您需要在dealer_id的实例中提供一个LoanRequest,它应该是一个Dealer实例,或者更改您的LoanRequest模型,以便{ {1}}字段包含dealer_id

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

答案 1 :(得分:0)

在没有blank=True的情况下指定null=True对于外键不是很有用。

改为使用此:

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

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