In my application I am trying to remove many to many records via loop:
org = current_user.Organization
for item in org.items:
if item.id in remove_ids:
org.items.remove(item)
db.session.commit()
However, it skips every second item. Since the list is modified in the loop. How could I solve it in a proper way?
>Solution :
Removing elements from a container in a loop typically doesn’t work.
I would suggest something along the lines of:
org = current_user.Organization
org.items = [item for item in org.items if item.id not in remove_ids]
db.session.commit()