[Answered ]-Django m2m and saving objects

2👍

Yes, the deletion of any existing rows in appname_obj1_obj2 is expected behavior when saving a form for an object that has a ManyToManyField.

You can see the clear() before the add(**values) in ReverseManyRelatedObjectsDescriptor and ManyRelatedObjectsDescriptor in django/db/models/fields/related.py.

Pop open a shell and take a look at the queries yourself. Something like this should show you the DELETE before the INSERT in the raw sql.

from django.db import connection
fm = FamilyMember.objects.get(pk=1)
form = FamilyMemberDetailsForm(instance=fm)
data = form.initial
data['name'] = "z%s" % data['name']  
form = FamilyMemberDetailsForm(data, instance=fm)
connection.queries = []  # clearing to limit the queries you have to look at
form.save()
for q in connection.queries:
    print("%s\n" % q['sql'])

Leave a comment