Сначала получите пользовательский объект,
>>> user = User.objects.get(id=some_user_id)
Когда мы используем функцию dir () , вы можете увидеть список всех доступных методов и атрибутов объекта user.groups
.
>>> dir(user.groups)
['__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slotnames__', '__str__', '__subclasshook__', '__weakref__', '_add_items', '_apply_rel_filters', '_build_remove_filters', '_constructor_args', '_db', '_get_queryset_methods', '_hints', '_insert', '_queryset_class', '_remove_items', '_remove_prefetched_objects', '_set_creation_counter', '_update', 'add', 'aggregate', 'all', 'annotate', 'auto_created', 'bulk_create', 'check', 'clear', 'complex_filter', 'contribute_to_class', 'core_filters', 'count', 'create', 'creation_counter', 'dates', 'datetimes', 'db', 'db_manager', 'deconstruct', 'defer', 'difference', 'distinct', 'do_not_call_in_templates', 'earliest', 'exclude', 'exists', 'explain', 'extra', 'filter', 'first', 'from_queryset', 'get', 'get_by_natural_key', 'get_or_create', 'get_prefetch_queryset', 'get_queryset', 'in_bulk', 'instance', 'intersection', 'iterator', 'last', 'latest', 'model', 'name', 'none', 'only', 'order_by', 'pk_field_names', 'prefetch_cache_name', 'prefetch_related', 'query_field_name', 'raw', 'related_val', 'remove', 'reverse', 'select_for_update', 'select_related', 'set', 'source_field', 'source_field_name', 'symmetrical', 'target_field', 'target_field_name', 'through', 'union', 'update', 'update_or_create', 'use_in_migrations', 'using', 'values', 'values_list']
Таким образом, вы можете работать со всеми методами и атрибутами групп пользователей, которые указаны в таблице auth_user_groups
.Для примера я выберу несколько таких, как set
, add
, remove
и clear
.
# you can set list of groups for the user
user.groups.set([group_list])
# you can add group one by one for the user
user.groups.add(group, group, ...)
# you can remove group one by one from the user
user.groups.remove(group, group, ...)
# you can clear all the groups which are belongs to the user
user.groups.clear()
Здесь вы можете узнать больше о Система аутентификации Django в документации.