-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
  • 110,080
  • 24
  • 357
  • 317
Tomas Am
  • 199
  • 2
  • 8

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
  • 2,239
  • 2
  • 6
  • 20