如何在不同的数据库中使用带有外键的 django 模型?

2021-12-19 00:00:00 django django-models foreign-keys mysql

我有 2 个模型用于 2 个不同的数据库:
数据库是手动创建的,但它应该没有任何改变.

I have 2 models for 2 different databases:
Databases were created manually but it should change nothing.

class LinkModel(models.Model): # in 'urls' database
    id = models.AutoField(primary_key=True)
    host_id = models.IntegerField()
    path = models.CharField(max_length=255)

    class Meta:
        db_table = 'links'
        app_label = 'testapp'

    def __unicode__(self):
        return self.path

class NewsModel(models.Model):  # in default database
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=50)
    link = models.ForeignKey(LinkModel)

    class Meta:
        db_table = 'news'
        app_label = 'test'

    def __unicode__(self):
        return self.title

在以下代码之后出现错误

After the following code an error raises

newsItem, created = NewsModel.objects.get_or_create( title="test" )
link = LinkModel.objects.using('urls').get( id=1 )
newsItem.link = link  # error!

 Cannot assign "<LinkModel: />": instance is on database "default", value is on database "urls"

为什么我不能为不同的数据库使用外键和模型?

Why can't I use foreign key and a model for different database?

推荐答案

跨数据库限制

Django 目前不支持跨多个数据库的外键或多对多关系.如果您使用路由器将模型分区到不同的数据库,则这些模型定义的任何外键和多对多关系都必须在单个数据库内部.

Cross-database limitations

Django doesn't currently provide any support for foreign key or many-to-many relationships spanning multiple databases. If you have used a router to partition models to different databases, any foreign key and many-to-many relationships defined by those models must be internal to a single database.

Django - limits-of-multiple-databases

同样的麻烦.ForeignKey() 类中的错误.

Same trouble. Bug in ForeignKey() class.

在 validate() 方法中.

In validate() method.

看票

Bug 存在于 v1.2、v1.3、v1.4rc1

Bug exists in v1.2, v1.3, v1.4rc1

尝试这个补丁来解决.

相关文章