跨数据库外键错误

时间:2014-04-24 12:28:28

标签: django foreign-keys cross-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:

    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

现在,当我打开Department表时,它给出了一个错误:

      ProgrammingError at /admin/leavebuddyapp/department/
      (1146, "Table 'leavebuddy_master.leavebuddyapp_department' doesn't exist")

我已经在两个数据库中正确完成了settings.py中的所有设置。你能指导我正确的方向吗?提前完成。

1 个答案:

答案 0 :(得分:8)

你说得对,Django目前不支持跨越多个数据库的外键关系。 来自Cross-database relations

  

如果您使用路由器将模型划分到不同的数据库,则由这些模型定义的任何外键和多对多关系必须是单个数据库的内部

     

这是因为参照完整性。为了维护两个对象之间的关系,Django需要知道相关对象的主键是有效的。如果主键存储在单独的数据库中,则无法轻松评估主键的有效性

我认为你可以尝试的解决方案(虽然它可能会出现其他问题):

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的问题。希望它有所帮助,或至少激发更好的解决方案!