【问题标题】:NOT NULL constraint failed for ForeignKey(null=True)ForeignKey 的 NOT NULL 约束失败(null=True)
【发布时间】:2020-05-09 08:47:41
【问题描述】:

我有两个模型,分别是Applicant 和LoanRequest。每当创建 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 非常陌生,非常感谢帮助!

【问题讨论】:

  • 抱歉,这与问题无关,但在外键字段名称中使用 _id 是多余的,实际上是不正确的。访问该属性,django 模型将返回被引用的实际对象,而不仅仅是它的 id。 django 自动创建的数据库列将附加_id,正如您在错误消息中的_id_id 中看到的那样
  • 那么你需要在create函数中传入dealer_id_id,其值为dealer申请者的id
  • 如果您正在使用现有数据库并迁移到 Django,您可以为您的字段使用db_column 选项参数,以使实际的 SQL 列名与 Django 字段名不同。否则,您可能不想使用_id 为外键字段添加后缀,因为您最终会得到两个属性myfield_id 和myfield_id_id,其中前者返回一个实例,后者实际上包含ID 值,这可能会造成混淆.
  • 我不小心将null=True 放在了问题标题中,这是一种误导,因为它是解决方案,ForeignKey(null=True) 不会导致这个问题。如果有人能纠正这个问题,我将不胜感激。非常感谢。

标签: python django database model foreign-keys


【解决方案1】:

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 - 这样做几乎总是不正确的。

【讨论】:

    【解决方案2】:

    指定 blank=True 而不指定 null=True 对于 ForeignKey 不是很有用。

    改用这个:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-22
      • 2018-08-24
      • 2022-01-19
      • 2021-11-16
      • 2020-12-18
      • 2021-03-20
      • 2020-02-11
      • 2019-02-13
      相关资源
      最近更新 更多