问题描述
现有两个模型,如下:
# mysite/reporter/models.py
from django.db import models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
# mysite/article/models.py
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, 但是当这两张表分别写入不同数据库时:
# INSTALLED_APPS = ['reporter', 'article']
# 配置两个 db
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 构建一个唯一性的字段来实现关联:
# mysite/reporter/models.py
from django.db import models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
mark = models.CharField(max_length=50, unique=True)
# mysite/article/models.py
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.CharField(max_length=50) # 对应 mark
还没找到更好的方法,只能先曲线救国了,希望大家可以提供更好的方法。