Add user to group to specific database does not work

Hai,
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)
user.groups.add(group)

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?

The groups in the expression user.groups.add(group) is a manager, similar to objects.

Try using using in that expression. (e.g., user.groups.using(...).add(group))

Actually, I’m surprised that the user.groups.add works when either user or group aren’t in the default database.

Hai,
Thanks.

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.

user.groups.add(group)

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 _instance._state.db
        else:
          return get_current_db_name()


def get_current_db_name():
        return getattr(THREAD_LOCAL, "DB", None)