So the following section from the docs has me a little confused:
=====================
Another side effect of using commit=False is seen when your model has a many-to-many relation with another model. If your model has a many-to-many relation and you specify commit=False when you save a form, Django cannot immediately save the form data for the many-to-many relation. This is because it isn't possible to save many-to-many data for an instance until the instance exists in the database.
To work around this problem, every time you save a form using commit=False, Django adds a save_m2m() method to your ModelForm subclass. After you've manually saved the instance produced by the form, you can invoke save_m2m() to save the many-to-many form data. For example:
# Create a form instance with POST data.
>>> f = AuthorForm(request.POST)
# Create, but don't save the new author instance.
>>> new_author = f.save(commit=False)
# Modify the author in some way.
>>> new_author.some_field = 'some_value'
# Save the new instance.
>>> new_author.save()
# Now, save the many-to-many data for the form.
>>> f.save_m2m()
======================
I can understand why Django doesn't save Many-to-Many data when commit is set to False, but why do we need to manually call save_m2m() after doing save() manually? Why doesn't Django update the associated Many-to-Many data automatically in this case?
Regards,
Ankush Thakur
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CALX%3DrK%2B1wQNHk5EJ_WqvEWdk%2BJ0BGnBen%3DmN9FLoc6OB%2Bh2Dqg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment