I have an application that mostly is composed of forms that create, modify, read, and deletes tables and establish relationships. I use SQLAlchemy. If, for example, I need to create an invoice and associate it to a customer and to an agent, from the salespeople of the company I use the following pattern:
1: Load mappings:
agent_name_id_map = {r.name, r.id for r in session.query(Agent)}
customer_name_id_map = {r.name, r.id for r in session.query(Customer)}
2: Build the invoice form, which, among other things, has two comboboxes, like:
agent_combo = ComboBox()
agent_combo.addItems(agent_name_id_map.keys())
customer_combo = ComboBox()
customer_combo.addItems(customer_name_id_map.keys())
3: The user wants to commit the form and after some validation, I execute, say, the save method:
def save(self):
invoice = Invoice()
···
invoice.agent_id = agent_name_id_map[agent_combo.getText()]
invoice.customer_id = customer_name_id_map[customer_combo.getText()]
···
session.add(invoice)
session.commit()
The code is like pseudocode. In the real app, I handle some exceptions, make validation, etc.
Is this a good mechanic for doing this?
These kinds of relationships are spread over the whole application, linking payments, expenses, documents, agents, partners, etc. I am not sure if I am doing well.