Django 两个外键
我有两个模型:UserProfile(从用户扩展)和Cv。我创建了另一个模型,它有两个来自这些模型的外键。
class cv(models.Model):
user = models.ForeignKey(User, unique=True)
cv_d= models.TextField(max_length=1100)
...
class cvv(models.Model):
user = models.ForeignKey(User)
cv= models.ForeignKey(cv)
date = models.DateTimeField(auto_now=True)
在我的视图中,我尝试在 cvv 上插入值:
...
obj = cv.objects.get(pk=id,active=True)
add=cvv(user=request.user, cv=obj)
add.save()
但是,我收到以下错误: (1452, '无法添加或更新子行:外键约束失败
如何在我的模型上插入这 2 个外键?
I have two models: UserProfile (extended from user) and Cv. I created another model that have two foreign key that come from theses models.
class cv(models.Model):
user = models.ForeignKey(User, unique=True)
cv_d= models.TextField(max_length=1100)
...
class cvv(models.Model):
user = models.ForeignKey(User)
cv= models.ForeignKey(cv)
date = models.DateTimeField(auto_now=True)
In my view, I am trying to insert value on cvv:
...
obj = cv.objects.get(pk=id,active=True)
add=cvv(user=request.user, cv=obj)
add.save()
But, I am getting the following error:
(1452, 'Cannot add or update a child row: a foreign key constraint fails
How can I insert theses 2 foreign key on my model?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
欢迎来到不应该使用 MySQL 的众多原因之一。当您有一张 MyISAM 表和一张 InnoDB 表时,最常发生这种情况。由于 myISAM 不支持 FK 约束,当 django 在表之间创建 FK 时,一切都会崩溃。
解决方法是要么将两个表设置为 InnoDB 或 MyISAM,而不是混合使用它们。或者甚至更好地放弃糟糕的 RDMS,而使用 MySQL 以外的东西。
Welcome to one of the many reasons why you shouldn't use MySQL. This happens most often when you have one table that is MyISAM and one table that is InnoDB. Since myISAM doesn't support FK constraints all hell breaks loose when django creates a FK between the tables.
The fix is to either make both tables InnoDB or MyISAM and not to mix them. Or even better drop the bad RDMS for something not MySQL.