I have run into a chicken and egg situation.
I have a formset where the user can modify existing data. The instance shall not be saved directly though but instead it shall be added as a new object.
for fm in attached_deals_formset:
if fm.has_changed():
modified_deal = fm.save(commit=False)
deal = Deal.objects.create(deal_id = modified_deal.deal_id, ... )
for item in modified_deal.sales_item: #m2m
deal.sales_item.add(item)
deal.save_m2m();
My problem is sales_item which is a m2m field. Just by traversing through it it crashes:
for item in modified_deal.sales_item:
‘Deal’ instance needs to have a primary key value before a
many-to-many relationship can be used.
I don’t understand though, these are the multi-selects that the user has selected within modified_deal, why does it throw an exception by just traversing through it? And how could I solve this?
I found the solution.
modified_deal = fm.save(commit=False)only contains the class values. The m2m fields point to separate tables and hence are not set yet.In order to get access to the m2m selection of the user, simply use that field as part of the
form.cleaned_data[]rather part of the model:This works for me.