SQLAlchemy列值基于另一个

时间:2018-05-21 12:42:10

标签: python sqlalchemy

我想知道是否可以根据SQLAlchemy中同一个表中的其他值来计算列值。

以下是我的例子:

from uuid import uuid4
from datetime import datetime

from sqlalchemy import Column, String, DateTime, UniqueConstraint
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


def generate_uuid():
    return str(uuid4())


class User(Base):
    __tablename__ = 'users'
    __table__args__ = (UniqueConstraint('username', 'email_address', 'phone'),)

    user_id = Column(String(36), primary_key=True, unique=True, default=generate_uuid)
    username = Column(String(15), nullable=False)
    password = Column(String(25), nullable=False)

    email_address = Column(String(255), nullable=False)
    phone = Column(String(20), nullable=False)

    hash = Column(String(128), nullable=False, unique=True)

    created_on = Column(DateTime(), default=datetime.utcnow)
    updated_on = Column(DateTime(), default=datetime.utcnow, onupdate=datetime.utcnow)

我想要实现的是在修改(更新)hashusernameemail_address时重新计算phone列。

这可以使用sqlalchemy.event.listen_for吗?如果是,可以在hash取决于多列时使用它吗?

1 个答案:

答案 0 :(得分:2)

您可以在sqlalchemy中使用mapper-events http://docs.sqlalchemy.org/en/latest/orm/events.html#mapper-events

before_update结束before_insert,然后你可以编辑你的实例:)

例如:

def before_insert_function(mapper, connection, target):
    # 'target' is your object
    print(target.user_id )
    print(target.password)
    target.hash = "Other"
event.listen(User, 'before_insert', before_insert_function)

@event.listens_for(User, 'before_update')
def before_insert_function(mapper, connection, target):
        # 'target' is your object
        print(target.user_id )
        print(target.password)
        target.hash = "Other"