好吧,之前问过的类似问题似乎对此没有一个有效的答案。我有一个Django应用程序,运行良好,但是现在在基于web的应用程序或命令行中使用这些模型,请告诉我上面的错误。我所有的表都是Innodb,我已经运行了syncdb。关闭完整性检查似乎有违直觉。如果我在这里或之前的答复中忽略了显而易见的内容,我很抱歉。任何帮助,谢天谢地。
来自models.py
class difficulty(models.Model):
difficultyName = models.CharField(max_length=40)
difficultyDescription = models.CharField(max_length=200)
blank=False;
def __unicode__(self):
return self.difficultyName
class task(models.Model):
question = models.CharField(max_length=200)
dateEntered = models.DateTimeField('date entered') #, editable=False)
difficulty = models.ForeignKey(difficulty)
taskClass = models.ManyToManyField(taskClass,related_name ='taskClass')
keyword = models.ManyToManyField(keyword)
service = models.ManyToManyField(service)#, default = service.objects.get(serviceName='Medicine'))
answer = models.ManyToManyField(answer, related_name = 'taskAnswer')
def __unicode__(self):
return "A task - {0}\n with difficulty {1}\n and date {2}\n".format(self.question, self.difficulty, self.dateEntered)在views.py中,对象被实例化并保存如下
if form.is_valid(): # All validation rules pass
theNewTask = form.save(commit=False)
theNewTask.dateEntered = timezone.now()
theNewTask.save() # the rest of the method deals with many-to-many relationships in the task class它在通过基于模板的web表单处理时会产生以下错误:
异常值:(1452,“无法添加或更新子行:外键约束失败(
djangoimp.twomt_task,constraintdifficulty_id_refs_id_eca4bfb0REFERENCES (difficulty_id) REFERENCESTwoMT_difficulty(id))”)
在python命令行中使用类:
>> import twomt.models as T
>> from django.utils import timezone
>> task = T.task(question="where is spain")
>> task.dateEntered = timezone.now()
>> task.difficulty = T.difficulty.objects.get(id=2)
>> task.save()给出错误:
回溯(最近一次调用):--狙击出跟踪-- IntegrityError:(1452,‘无法添加或更新子行:外键约束失败(
djangoimp.twomt_task,constraintdifficulty_id_refs_id_eca4bfb0foreign key (difficulty_id) REFERENCESTwoMT_difficulty(id))“)
但是实例化的类很好:
>>> print task
A task - where is spain
with difficulty Medium
and date 2015-03-19 11:19:04.494322+00:00
>>> print T.difficulty.objects.get(id=2)
Medium显示来自TwoMT_task的列
Field Type Null Key Default Extra
'question', 'varchar(200)','NO', '' , NULL, ''
'id', 'int(11)', 'NO', 'PRI', NULL, 'auto_increment'
'difficulty_id','int(11)', 'NO', 'MUL', NULL, ''
'dateEntered', 'datetime', 'NO', ' ', NULL, ''显示来自twomt_difficulty的列
Field Type Null Key Default Extra
'id', 'int(11)', 'NO', 'PRI', NULL, 'auto_increment'
'difficultyName', 'varchar(40)', 'NO', '', NULL, ''
'difficultyDescription','varchar(200)','NO', '', NULL, ''发布于 2020-10-22 00:41:41
我也有同样的问题,用这个链接解决了:
简历(从链接):
生成错误1452 (23000)是因为引用表顺序的子列cid中的某些当前值不在被引用表客户的父列id中。在我们真正创建它之前,它已经违反了约束规则。因此,MySQL无法创建约束。
解决方案
所以现在,您必须识别违反约束的行并纠正它们。这工作辛苦吗?不怎么有意思。您可以使用以下语句标识行:
mysql> select * from orders where cid not in (select distinct id from customers);https://stackoverflow.com/questions/29147809
复制相似问题