[Django]-Django add to many to many field working without save

4๐Ÿ‘

โœ…

If you do not update a field of the group (not a ManyToManyField because these are implemented with a hidden table), then saving the group makes no sense.

Django implements a ManyToManyField with a junction table [wiki]. This means that it constructs a extra table with two ForeignKeys: one to the model where you define the ManyToManyField, and one to the target of that field.

In case you want to add a link to the request.user it thus will not update the table behind the Group model. It will simply insert an extra entry in the junction table where it populates the ForeignKey to the Group model with the primary key of group, and the ForeignKey to the user model with the primary key of request.user.

This thus means that adding, removing, clearing, etc. the many-to-many relation will not make changes to the Group object, and hence it should not be saved. By saving it, you make a useless query.

Leave a comment