I'm using a API payload to update a database. I have some business rules enforced by Foreign Key Constraints, like: Address must have a Customer ID associated to it (One Customer <-> Many Address').
When updating the database, I have to make sure that all or nothing is committed, in order not to update one table and update another, so I write the update step by step:
- Update customers
- Update address
- Commit all changes
Basically I use a list of classes instances to call add_all(), and just committing after both add_all. Where id is the PK on customers, and the FK on address.
customers_list = []
customer_entry = Customers(name=name, id=id)
customer_list.append(entries)
db.session.add_all(customer_list)
address_list = []
address_entry = Address(id=customer_id, zip=zip)
address_list.append(entries)
db.session.add_all(address_list)
db.session.commit()
The thing is, when it gets to address', it gives me an Integrity Error, since it can't find the customer_idon the Customers table (since it hasn't been committed).
I though about disabling the Foreign Key Constraing for a while, but it doesn't seem a good way to ensure a solid database.
How do I maintain consistency while avoiding integrity errors (FK constraint)?