I have two models, namely Applicant
and LoanRequest
. Whenever an Applicant
instance is created, a signal is sent to a function that makes an API call. The data from the call, along with the primary key of the instance that sent the signal, is saved to as a LoanRequest
.
When I save the LoanRequest
, however, it gives the following error:
django.db.utils.IntegrityError: NOT NULL constraint failed: queues_loanrequest.dealer_id_id
Here's my code:
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"])
Very new to Django, would greatly appreciate help!
LoanRequest
has a field
dealer_id = models.ForeignKey(Dealer, on_delete=models.CASCADE,blank=True)
Because dealer_id
doesn't have null=True
, creating a LoanRequest
instance without supplying a dealer_id
will raise the database error you've got.
You need to either supply a dealer_id
in the instantiation of the LoanRequest
, which should be a Dealer
instance, or else change your LoanRequest
model so that the dealer_id
field has null=True
.
Please see comment above re: using the suffix _id
on a Django model foreign key - it's nearly always incorrect to do so.
Specifying blank=True
without null=True
is not very useful for a ForeignKey.
Use this instead:
dealer_id = models.ForeignKey(Dealer, on_delete=models.CASCADE, blank=True, null=True)
This would make the field optional. Otherwise, you would have to specify the Dealer
every time you create a LoanRequest
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.