Rajiv Gupta
Rajiv Gupta

Reputation: 111

Django Integrity Error 1452, Cannot add or update a child row: a foreign key constraint fails

models.py:

from django.db import models

class Line(models.Model):
  text = models.CharField(primary_key=True, max_length=255)

class Line2 (models.Model):
  text_line = models.ForeignKey ("Line", primary_key = True)

views.py:

from django.core.context_processors import csrf
from django.shortcuts import render
import datetime
from models import Line, Line2

def test_page (request):
  if 'uid' in request.POST:
    user_id = request.POST['uid']
    line_query = Line.objects.get (text = user_id)
    new_entry = Line2 (text_line_id = line_query)
    new_entry.save()
    return render(request, "templateFiles/testPage1.html", {"page_result":"Data Entered"});
  else:
    return render(request, "templateFiles/testPage1.html")

template:

<div id = "header">
  {{ page_result }}
  <form action="http://127.0.0.1:8000/test_page/" method = "POST">
    {% csrf_token %}
    <input type="text" id="uid" name="uid" />
    <input type="submit" id="submit" value="Submit" />
  </form>
</div>

The data which I'm sending exists in the parent key, but I'm getting

IntegrityError

(1452, 'Cannot add or update a child row: a foreign key constraint fails (tempDB.testDBProjectApp_line2, CONSTRAINT text_line_id_refs_text_f741df88 FOREIGN KEY (text_line_id) REFERENCES testDBProjectApp_line (text))')

My Database Parent Table "line" is as follows:

 mysql> select * from testDBProjectApp_line;
 +-------+
 | text  |
 +-------+
 | test1 |
 | test2 |
 +-------+

Upvotes: 5

Views: 10803

Answers (2)

khansahab
khansahab

Reputation: 11

You may try with giving the foreign key to related_name.

also verify this: Is the parents table have a record which you are filtering from query.

Upvotes: 1

Alasdair
Alasdair

Reputation: 308789

You shouldn't assign the Line instance to text_line_id as you are currently doing.

You should either do

new_entry = Line2(text_line=line_query)

or

new_entry = Line2(text_line_id=line_query.text)

Upvotes: 3

Related Questions