On my website any user have only one group. And any user can change his group.
So it’s made by
user.groups.clear()
and
user.groups.add(new_group)
But it’s not efficient, because there is a two SQL query: DELETE, INSERT.
How can I change group by just UPDATE query?
UserandGroupare related to each other using aManyToManyField. That means an intersection table exists relating both entities, and if you don’t specify a model to map to it (using thethroughattribute) Django creates one for you. Looking at the sources fordjango.contrib.auth.modelsI see that’s the case.Fortunatly, you can access that intermediary model using the
throughattribute of the manager (in this case,User.groups.through). Then you can use it just like any regular model. Example:(newlines added for readability)