跨数据库外键错误 [英] Cross Database foreign key error
问题描述
这是我第一个数据库DB1的模型:
This my model of first Database DB1:
from django.db import models
class Company(models.Model):
name = models.CharField(max_length=100, null=True)
address = models.TextField(max_length=200, null=True)
website = models.CharField(max_length=200, null=True)
conatct_no = models.CharField(max_length=20, null=True)
email = models.EmailField(max_length=20, null=True)
logo = models.FileField(upload_to='logo/', blank=True, null=True)
created = models.DateTimeField('company created', auto_now_add=True)
updated = models.DateTimeField('company updated', auto_now=True, null=True)
def __unicode__(self): # Python 3: def __str__(self):
return self.name
第二个数据库Db2的模型:
Model of 2nd Database Db2:
from django.db import models
from leavebuddymaster.models import Company
class Department(models.Model):
company = models.ForeignKey(Company)
department_name = models.CharField(max_length=50, null=True)
created = models.DateTimeField('department created', auto_now_add=True)
updated = models.DateTimeField('department updated', auto_now=True, null=True)
def __unicode__(self): # Python 3: def __str__(self):
return self.department_name
现在,当我打开部门"表时,出现以下错误:
Now when i open the Department table it gives me a error as:
ProgrammingError at /admin/leavebuddyapp/department/
(1146, "Table 'leavebuddy_master.leavebuddyapp_department' doesn't exist")
我已经正确地为两个数据库完成了settings.py中的所有设置.你能指导我正确的方向吗?提前感谢.
I have done all the settings in settings.py correctly for the two databases. Can you please guide me in the right direction. Thanx in advance.
推荐答案
您是正确的,Django当前不支持跨多个数据库的外键关系. 来自跨数据库关系 [Edit 2020:Django version凹凸] :
You're correct, Django does not currently support foreign key relationships spanning multiple databases. From Cross-database relations :
如果您已使用路由器将模型分区到不同的数据库,则这些模型定义的任何外键和多对多关系必须在单个数据库内部.
这是因为参照完整性.为了维持两个对象之间的关系,Django需要知道相关对象的主键有效.如果主键存储在单独的数据库中,则无法轻松评估主键的有效性.
This is because of referential integrity. In order to maintain a relationship between two objects, Django needs to know that the primary key of the related object is valid. If the primary key is stored on a separate database, it’s not possible to easily evaluate the validity of a primary key.
我认为您可以尝试使用的解决方案(尽管它可能会出现其他问题):
A solution I thought up that you could try (though it may present other problems):
from leavebuddymaster.models import Company
class Department(models.Model):
company_id = models.IntegerField()
@property
def company(self):
return Company.objects.get(pk=self.company_id)
这使您可以像在示例中通常一样引用Department.company
.设置它只是Department.company_id = Company.pk
的问题.希望它会有所帮助,或者至少会激发出更好的解决方案!
This allows you to refer to Department.company
like you normally would in your example. Setting it would just be a matter of Department.company_id = Company.pk
. Hope it helps, or at least inspires a better solution!
这篇关于跨数据库外键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!