I am struggling to make the following code works for me.
user = User.objects.using(data[‘db_name’]).get(pk=1)
group = Group.objects.using(data[‘db_name’]).get(pk=2)
I can see that Django creates one record to auth_user_groups in the default database but not in the data[‘db_name’]) database. Interestingly, user and group objects are coming from data[‘db_name’] database.
Can anyone advise me how to add new record to data[‘db_name’] database successfully?
groups in the expression
user.groups.add(group) is a manager, similar to
using in that expression. (e.g.,
Actually, I’m surprised that the
user.groups.add works when either
group aren’t in the default database.
Just to confirm the above code works but I have custom db route that unexpectedly creates related table records to default database and not the database of parent object. I ended up changing my db route’s write function to get the correct database name.
So when db_for_write function gets called I get database name from **hint which is the same database as user object and that is what I needed.
def db_for_write(self, model, **hints):
if hints.get('instance') is not None:
_instance = hints['instance']
return getattr(THREAD_LOCAL, "DB", None)