Issue
Does anyone know how to assign a user to a group (to a specific database)?
I know how to read / create record to specific database but not really sure how to create related table record to specific database. And Django offical documentation is not really clear about it.What will be the syntax in this case?
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
user = User.objects.using('db').get(pk=1)
admin_group = Group.objects.using('db').get(name='admin')
# Below line does not work.
user.groups.add(admin_group)
The last line does not really seem to create any record to auth_user_groups table. Instead it creates record to default database. How to specify database in the last line?
Solution
Just to confirm the above code works but I had a custom db route that changes Django's default behaviour.
I ended up changing my db_for_write as below to specify which database to pick. I noticed while executing user.groups.add(admin_group), db_for_write function gets called and I look for correct database name from **hint which was the desired database.
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)
Answered By - kta
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.