You are right, I misinterpreted Mike's suggestion.  I expected "Unit of 
work" to be an code process but it's a concept.  The changes to related 
data rows of the table in the recipe unit must be handled by my python code 
not SqlAlchemy.  Since reading your comments, I have begun to develop a 
general process: handle the row deletions (if any) first then the updates 
and finally the inserts.  Flagging changes to the table rows as they occur 
seems to be the way to go.

On Friday, August 28, 2020 at 12:51:30 PM UTC-4 Jonathan Vanasco wrote:

> I believe your error is tied to this section of code:
>
>  
>
>>     for item in ingredDict:
>>         ingredient_item = 
>> Ingredients(ingredientKey=item['ingredientKey'], 
>>                                      
>> ingredientDescription=item['ingredientDescription'],
>>                                      ingredientRecipeKey=recipeKey,
>>                                      
>> ingredientQuantity=item['ingredientQuantity'])
>>         Ingredients_item_object_list.append(ingredient_item)
>
>
> It looks like you are iterating through this dict, creating new 
> ingredients, and adding them to the recipe/database.
>
> This is fine for CREATE, but is raising an integrity error on UPDATE 
> because the ingredients already exist and you are creating a new entry on 
> every iteration.
>
> A lazy way to address this would be something like: remove all the 
> existing ingredients, flush, then run this loop. 
>
> A common way to handle this is the bit of Mike's suggestion which you 
> missed: calculate the differences between the set of old and new items to 
> determine which ingredients need to be added or removed (or updated, as 
> that seems possible now).  Within the Unit of Work, as mike said, you need 
> to delete and add (and also update it would seem).
>
>

-- 
SQLAlchemy - 
The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

To post example code, please provide an MCVE: Minimal, Complete, and Verifiable 
Example.  See  http://stackoverflow.com/help/mcve for a full description.
--- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sqlalchemy/c84e74e8-7145-40da-b3ff-33b3f31ad436n%40googlegroups.com.

Reply via email to