Note that there are some explanatory texts on larger screens.

plurals
  1. POSave or update for FK relationship Sqlalchemy
    text
    copied!<p>I've googled, but haven't been able to find the answer to this seemingly simple question.</p> <p>I have two relations, a customer and an order. Each order is associated to a single cusomter, and therefore has a FK relationship to the customer table. The customer relation only stores customer names, and I have set a unique constraint on the customer table barring duplicate names.</p> <p>Let's say I create a new order instance and set a customer for the order. Something like:</p> <pre><code>order_instance.customer = Customer("customer name") </code></pre> <p>When I save the order instance, SqlAlchemy will complain if a customer with this name already exists in the customer table.</p> <p>How do I specify to SqlAlchemy to insert into the customer table if a customer with this name doesn't already exist, or just ignore (or even update) to the customer relation? I don't really want to have to check each time if a customer with some name already exists...</p> <p>----Edit--- The Customer table has a unique constraint set on it, such that no two customers can have the same name. Singletoned, using your current implementation, an IntegrityError is getting thrown. If a customer with this name already exists, return that Customer instance. Otherwise, return a new Customer instance.</p> <p>It seems that SqlAlchemy, no matter if the customer already exists or not, is trying to execute a SQL insert statement into the Customer table. Perhaps I have my cascades set incorrectly?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload