Home > Mobile >  How to access auth_user_group table by ID
How to access auth_user_group table by ID

Time:02-11

How can I directly specify the ID column of auth_user_group table in queries/DML?

I am referring to auth_user_group.id, not auth_group.id nor auth_user_group.group_id.

For example, I want to directly issue DML like:

delete from auth_user_group where auth_user_group.id = 1

select id, user_id, group_id from auth_user_group where auth_user_group.id = 1;

I am not interested in the following workaround which avoids auth_user_group by requiring knowledge of the group name, instead of the auth_user_group.id, and results in two queries instead of 1:

group = Groups.get(name='foo')
user.groups.remove(group)

If you wanted to directly query a junction/M:N table in Django, normally you would create a "through Model" and can then query it directly. However in this case, the django.contrib.auth.models definition do not use a through model. I'm willing to create a custom AbstractUser where groups is defined as a through table if that would work. But I'm not sure how to specify the through table since auth_user_group does not have its own model in django.contrib.auth.models.

CodePudding user response:

Since there is no explicit through model, you can access the implicit through model

Group.user_set.through.objects.get(id=1)

or

User.groups.through.objects.get(id=1)

https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ManyToManyField.through

  • Related