import datetime
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer, DateTime
from sqlalchemy import String
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
Base = declarative_base()
class User(Base):
__tablename__ = "user"
id = Column(Integer, primary_key=True)
name = Column(String(30),unique=True,default="")
fullname = Column(String(200), default="")
value = Column(Integer, default=0)
time_created = Column(DateTime(timezone=True), server_default=func.now())
time_updated = Column(DateTime(timezone=True), onupdate=func.now())
def __repr__(self):
return f"User(id={self.id!r}, name={self.name!r}, fullname={self.fullname!r})"
# Connection
from sqlalchemy import create_engine
engine = create_engine("postgresql+psycopg2://scott:tiger@localhost:5432/mydatabase")
# Insertar
with Session(engine) as session:
c = User(
name="juan",
fullname="perez",
)
session.add_all([c])
session.commit()
# Actualizar
with Session(engine) as session:
# stmt = select(User).where(User.name == "juan")
# r = session.execute(stmt).first()["User"]
r = session.query(User).filter(User.name == "juan").first()
print(r.value)
r.value += 2
print(r.value)
session.commit()
Referencias