-1

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?

davidism
  • 121,510
  • 29
  • 395
  • 339
Tomas Am
  • 433
  • 4
  • 13

1 Answers1

0

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()
Paul P
  • 3,346
  • 2
  • 12
  • 26