from django.db import models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
Article 关联 Reporter, 但是当这两张表分别写入不同数据库时:
python manage.py makemigrations reporter article
python manage.py migrate reporter --database reporter_db
python manage.py migrate article --database article_db
django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')
出现上面错误,是因为 django 本身不支持通过外键进行跨数据库关联,即便修改了数据库路由中的 allow_relation 方法,也不可以通过外键进行查询。
为了使两个 modle 依旧存在于两个不同的数据库,目前的解决办法是 通过在 Reporter 构建一个唯一性的字段来实现关联:
from django.db import models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
mark = models.CharField(max_length=50, unique=True)
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.CharField(max_length=50)
还没找到更好的方法,只能先曲线救国了,希望大家可以提供更好的方法。
Cannot add foreign key constraint问题描述解决方法问题描述现有两个模型,如下:# mysite/reporter/models.pyfrom django.db import modelsclass Reporter(models.Model): full_name = models.CharField(max_length=70) # mysite/article/models.pyclass Article(models.Model):
最近在做新生入学系统,学生表中包括新生的班级,专业等信息,班级,专业就需要和班级表,专业表进行关联,但是在添加外键的过程中却出现了“Cannot add foreign key constraint” 的问题,也就是不能添加外键约束,为什么就不能添加外键呢?
出现这个问题主要有三个原因:
(1)外键对应的字段数据类型不一致
(2)设置外键时“删除时”设置为“SET NULL”
用Navicat为mysql数据库的两个表之间建立外键关系,出现“cannot add foreign key constraint”错误,当时真的不知道是怎么回事儿,~~~~(>_
外键建立:
把表t_stuschoolregisterinfo的IDCard字段设成外键,关联表t_stupersoninfo的IDCard字段。
打开Navicat找到t_stuschoolre
File "C:\Python38\lib\site-packages\pymysql\cursors.py", line 163, in execute
result = self._query(query)
File "C:\Python38\lib\site-packages\pymysql\cursors.py", line 321, in _query
conn.query(q)
File "C:\Python38\lib\site-packages\p
错误信息:
1、django.db.utils.IntegrityError: (1215, u'Cannot add foreign key constraint')
2、RuntimeError: Error creating new content types. Please make sure contenttypes is migrated before trying to migr...
Django “Cannot add or update a child row: a foreign key constraint fails”
DATABASES = {
‘default’: {
‘OPTIONS’: {
“init_command”: “SET foreign_key_checks = 0;”,