I decided to learn something about the database with python (before I had used flask with sqlalchemy), the thing is that I want to update an element of the database, with flask and sqlalchemy it was simple, you just updated a class and did the commit but without apparently flask is more complex (I'm not sure) a function is used update()
, in summary I want to know how to use the function update()
to edit the element, I leave you my code
def AddProduc():
producto = Producto()
print ("\t\t .: Agregar Producto :. ")
producto.product_id = raw_input("\t ID del producto ( codigo de barras ): ")
Exist_Product = session.query( Producto ).filter_by( product_id = producto.product_id ).first()
# AGREGAR O ACTUALIZAR
if Exist_Product == None:
producto.nombre = raw_input("\t Nombre del producto: ")
producto.precio = input("\t Precio del producto: ")
producto.cantidad = input("\t Cuantos productos va a agregar: ")
session.add( producto )
session.commit()
else:
Cantidad_Nuevo = input("\t Cuantos productos va a sumar: ")
Cantidad_Nuevo = Cantidad_Nuevo + Exist_Product.cantidad
# Lo que esta adentro de update() es el nombre de la tabla no la clase
session.update( producto ).values( cantidad = Cantidad_Nuevo ).where()
The table is declared like this:
class Producto( db ):
__tablename__ = "producto"
product_id = Column( Integer(),primary_key = True )
precio = Column( Integer())
cantidad = Column( Integer())
nombre = Column( String(50))
Thanks in advance <3
You have several ways to update the field, for example:
Directly modify the attribute of the object:
sqlalchemy.orm.query.Query.update
sqlalchemy.sql.expression.update
/sqlalchemy.schema.Table.update
:Complete reproducible example based on the code in the question and using sqlite3:
A few small observations:
The correct way to tell if an object is
None
is to use the operatoris
, not the equality operator:As a general rule don't use
input
for user input in Python 2, it's not for inputting numeric values. Useraw_input
and an explicit casting toint
.It's a good idea to follow the style conventions defined in PEP 8 as much as possible. The names of variables, methods and functions must be lowercase and used
_
to separate words. Reserve CamelCase for classes and all caps for "constants".