Home > Enterprise >  Django add to many to many field working without save
Django add to many to many field working without save

Time:10-05

What's the difference between

group.reportedBy.add(request.user)
group.save()

AND

group.reportedBy.add(request.user)

It gets saved to the DB even without me doing .save()

CodePudding user response:

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.

  • Related