django - How can I change user group without delete record -
on website user have 1 group. , user can change group. it's made
user.groups.clear() and
user.groups.add(new_group) but it's not efficient, because there 2 sql query: delete, insert. how can change group update query?
user , group related each other using manytomanyfield. means intersection table exists relating both entities, , if don't specify model map (using through attribute) django creates 1 you. looking @ sources django.contrib.auth.models see that's case.
fortunatly, can access intermediary model using through attribute of manager (in case, user.groups.through). can use regular model. example:
>>> alice = user.objects.create_user('alice', 'alice@example.com', 'alicepw') >>> employee = group.objects.create(name='employee') >>> manager = group.objects.create(name='manager') >>> alice.groups.add(employee) >>> alice.groups.all() [<group: employee>] >>> alice_group = user.groups.through.objects.get(user=alice) >>> alice_group <user_groups: user_groups object> >>> alice_group.group = manager >>> alice_group.save() >>> alice.groups.all() [<group: manager>] >>> (newlines added readability)
Comments
Post a Comment