My project uses Django's builtin multi-database support and I am trying to synchronize data in 2 different databases by taking a record from one database and inserting it into another one.
I have tried to do this in the usual way using the add method of the RelatedManager, but it did not work and did not insert the record in the intermediary table in the second db, but rather did that in the default db.
Here is how I did that: I have a Person model which has a ManyToMany field to Dbs model:
...
class Person(models.Model):
...
tenant_dbs = models.ManyToManyField(to=Dbs, blank=True)
and Dbs model which contains a single column with the names of the databases a person can have access to:
...
class Dbs(models.Model):
person_id = models.CharField(primary_key=True,
max_length=20
)
So I want to get some Person, Dbs and intermediary records from the default database and copy them all to another database (let's assume its name is 'secondary'). So I do the following:
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)
I clearly see that no record is added to the table person_tenantdbs which was automatically created as the intermediary table on the database level in the 'secondary' db.
So I would like to know how to deal with that and insert a record into this table if the db is not default?
I already tried using manager as described here, like this:
...
p2.tenant_dbs.db_manager('secondary').add(d)
but it still does not work.
According to the Django source code, it seems like this method only takes the db provided by router in case of multi-db scenario, see here:
db = router.db_for_write(self.model, instance=self.instance)
So, is there a way to insert it and manually assign the db, or this can only be done with the router exclusively?
I would like to ask for help with this and would really appreciate it.