My problem seems far from solved. Searching the internet for information on how to apply "unit of work" has proven difficult. I found general references but no practical examples on how to concretely apply the concept. I finally found one practical (but short) explanation at :
Link to Unit of WorkMy application of the code on an SQLite database adjusting the code to my data model.
The database model
class Recipe(Base):
__tablename__ = 'tblRecipe'
recipeKey = Column(Integer, primary_key=True)
recipeName = Column(String(100))
recipeCategory = Column(Integer, ForeignKey("tblCategory.categoryKey"))
recipeDescription = Column(String(500))
ingredient = relationship("Ingredients", cascade="save-update, merge,delete, delete-orphan",
backref='tblRecipe', uselist=True)
class Catagory(Base):
__tablename__ = 'tblCategory'
categoryKey = Column(Integer, primary_key=True)
categoryName = Column(String(100))
class Ingredients(Base):
__tablename__ = 'tblIngredients'
ingredientKey = Column(Integer, primary_key=True)
ingredientDescription = Column(String(100))
ingredientRecipeKey = Column(Integer, ForeignKey("tblRecipe.recipeKey"))
ingredientQuantity = Column(String(100))
recipe = relationship("Recipe", back_populates="tblIngredients")
====================================================================================
The code: (my last modification) but like my other versions it does not work.
def updateRecipe(data):
session = connectToDatabase()
ingredDict = data.pop('Ingredients')
recipeKey = data['Recipe'].pop('recipeKey')
recipe = session.query(Recipe).filter(Recipe.recipeKey == recipeKey).one()
recipe.recipeName = data['Recipe']['recipeName']
recipe.recipeCategory = data['Recipe']['recipeCategory']
recipe.recipeDescription = data['Recipe']['recipeDescription']
Ingredients_item_object_list = []
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)
recipe.ingredient=Ingredients_item_object_list
session.add(recipe)
session.commit()
session.close()
The error message is:
"The debugged program raised the exception unhandled sqlalchemy.excIntegrityError.
(sqlite3.IntegityError) UNIQUE constraint failed: tblIngredients.ingredientKey[SQL:INSERT INTO "tblIngredients"("ingredientKey", "ingredientDescription", "ingredientRecipeKey", "ingredientQuantity") VALUES (?,?,?,?)] [parameters: (('60','Butter or Margerine', 23, '4 tablespoons'), ('61', 'Beef..', 23, '2'), ('62',....),('64', ..),(...))] (Background on this error at:
http://qlalche.me/e/13/gkpj)" File: /home.....
To shorten the error message I have eliminated some of the data to be updated and the file and line location.
Can anyone help?