models.py: Django的完整性錯誤1452,無法添加或更新子行,外鍵約束失敗
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,「不能添加或更新子行,外鍵約束失敗(
tempDB
。testDBProjectApp_line2
,約束外鍵(text_line_id
)參考文獻testDBProjectApp_line
(text
))')
我的數據庫父表中 「行」 如下:
mysql> select * from testDBProjectApp_line;
+-------+
| text |
+-------+
| test1 |
| test2 |
+-------+
即使有規定,那(我不知道),它真的就沒有意義。父關係元組可以被多個子關係元組引用 - 從而打破了主鍵附帶的唯一性約束。你可能會改變'primary_key = True'到'unique = True' – itzMEonTV
在Django中,聲明一個沒有主鍵的模型會導致創建一個自動的「id」字段並將其設置爲主鍵。如果我不想要額外的專欄會怎麼樣? 我創建了一個更多的模型,它工作正常。但我想知道爲什麼別人不工作。 還有一個觀察: 如果我嘗試「new_entry = Line2(text_line_id ='text1')」(即一個常數值),它的工作原理絕對沒問題。 我也檢查了來自HTML模板的值,它們也是正確的。 –
我試過多次刪除數據庫,更改列名然後運行syncdb。沒有工作! 我做了: mysql> drop database tempDB; mysql> create database tempDB; $ sudo python manage.py syncdb –