使用多个数据库时将记录插入表的"多对多"字段



我的项目使用 Django 的内置多数据库支持,我正在尝试通过从一个数据库中获取记录并将其插入另一个数据库来同步 2 个不同数据库中的数据。

我尝试使用 RelatedManager 的add方法以通常的方式执行此操作,但它不起作用,并且没有在第二个数据库的中间表中插入记录,而是在默认数据库中插入。

以下是我是如何做到的: 我有一个人员模型,它有一个多对多字段到Dbs模型:

...
class Person(models.Model):
...
tenant_dbs = models.ManyToManyField(to=Dbs, blank=True)

和 Dbs 模型,其中包含单个列,其中包含用户可以访问的数据库的名称:

...
class Dbs(models.Model):
person_id = models.CharField(primary_key=True,
max_length=20
)

所以我想从默认数据库中获取一些 Person、Dbs 和中间记录,并将它们全部复制到另一个数据库(假设它的名称是"辅助"(。所以我做了以下几点:

from core.models import Person
from .models import Dbs
#  here I take the objects from default db as I did not mention any other
#  db manually and save them in the 'secondary' db. This works fine and 
#  the records are duplicated to the db 'secondary'
p = Person.objects.get(pk='111')
p.save(using='secondary')
d = Dbs.objects.get(pk='some_db')
d.save(using='secondary')
# and now I retrieve the newly inserted records from the 'secondary' db and 
#  create a relation (insert a record into intermediary table, in other words)
#  using *add* method:
p2 = Person.objects.using('secondary').get(pk='111')
d2 = Dbs.objects.using('secondary').get(pk='some_db')
# **here is the problem: record is again inserted into default db
#  although it was retrieved from the 'secondary db'!**
p2.tenant_dbs.add(d) 

我清楚地看到没有记录添加到表中,person_tenantdbs该表是在"辅助"数据库中的数据库级别自动创建为中间表的。

所以我想知道如何处理这个问题,如果 db 不是默认值,则在此表中插入一条记录?

我已经尝试使用管理器,如下所述,如下所示:

...
p2.tenant_dbs.db_manager('secondary').add(d) 

但它仍然不起作用。

根据 Django 源代码,在多数据库场景下,这种方法似乎只占用路由器提供的 db,请参见此处:

db = router.db_for_write(self.model, instance=self.instance)

那么,有没有办法插入它并手动分配数据库,或者这只能通过路由器来完成?

我想寻求帮助,并将不胜感激。

这不是因为以多加。您只是忘记使用"使用"方法。

您应该更改这些

p = Person.objects.get(pk='111')
d = Dbs.objects.get(pk='some_db')

p = Person.objects.using('secondary').get(pk='111')
d = Dbs.objects.using('secondary').get(pk='some_db')

最新更新