Beispiel #1
0
    def add_favorite_substitute(sql, message, category, product, substitute):
        """
        Method to save a favorite in the database
        arg : SQL - Global instance of the sql class
              message - Global instance of the Message object
              category of the product/substitute
              Instance of a product
              Instance of a substitute

        return an instance of the saved Favorite if save performed
        else None
        """
        id_product = ""
        id_category = ""

        # Retrieve the id of the category in the database
        category_from_db = sql.select_first_row_one_attribute_where(
            "category", "id", ("id", product.id_category))
        # if the category was not found in the database
        if category_from_db is None:
            message.not_in_db("category : " + category)
            category = Category(message, category)
            # save the category in the database
            id_category = category.save_in_db(sql)
        else:
            id_category = category_from_db[0]
        # Retrieve the id of the product in the database
        product_from_db = sql.select_first_row_one_attribute_where(
            "product", "id", ("name", product.name))
        # if the category was not found in the database
        if product_from_db is None:
            message.not_in_db("product : " + product.name)
            # save the product in the database
            id_product = product.save_product_in_db(sql, id_category)
        else:
            id_product = product_from_db[0]

        id_substitute = ""
        # Retrieve the id of the substitute in the database
        substitute_from_db = sql.select_first_row_one_attribute_where(
            "product", "id", ("name", substitute.name))
        # if the substitute was not found in the database
        if substitute_from_db is None:
            message.not_in_db("substitute : " + substitute.name)
            # save the substitute in the database
            id_substitute = substitute.save_product_in_db(sql, id_category)
        else:
            id_substitute = substitute_from_db[0]

        # Save the favorite in the database
        substitute_dic = {
            "id_product": id_product,
            "id_substitute": id_substitute
        }
        id_favorite = sql.insert("substitute", **substitute_dic)
        if id_favorite > 0:
            return Favorite(message, substitute.name, id_product,
                            id_substitute)
        else:
            return None