Django完整性错误1452,无法添加或更新子行:外键约束失败

时间:2015-11-13 09:27:38

标签: python mysql django

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")

模板:

<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>

我发送的数据存在于父密钥中,但我正在

IntegrityError

  

(1452,&#39;无法添加或更新子行:外键约束失败(tempDBtestDBProjectApp_line2,CONSTRAINT text_line_id_refs_text_f741df88 FOREIGN KEY(text_line_id )参考testDBProjectApp_linetext))&#39;)

我的数据库父表&#34;行&#34;如下:

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

1 个答案:

答案 0 :(得分:2)

您不应该像当前那样将Line实例分配给text_line_id

你应该做

new_entry = Line2(text_line=line_query)

new_entry = Line2(text_line_id=line_query.text)