Python sqlalachmey根据特定条件将对象添加到数据库

Python sqlalachmey根据特定条件将对象添加到数据库,python,sqlalchemy,Python,Sqlalchemy,正如您所知,在Stackoverflow这样的网站中,当您的声誉达到某个特定值,或者当您回答与特定标签相关的一定数量的问题时,您将获得一枚徽章。如何实现这一点? 例如,如果我想在一个用户的声誉达到500时给他一个徽章,我是否应该在声誉改变时检查他的声誉,看看它是否为500? 我真的不知道这件事。假设这些是我的账户和徽章模型 association_table = Table( 'account_badge', DeclarativeBase.metadata, Column('a

正如您所知,在Stackoverflow这样的网站中,当您的声誉达到某个特定值,或者当您回答与特定标签相关的一定数量的问题时,您将获得一枚徽章。如何实现这一点? 例如,如果我想在一个用户的声誉达到500时给他一个徽章,我是否应该在声誉改变时检查他的声誉,看看它是否为500? 我真的不知道这件事。假设这些是我的
账户
徽章
模型

association_table = Table(
    'account_badge', DeclarativeBase.metadata,
    Column('account_id', Integer, ForeignKey('accounts.id')),
    Column('badge_id', Integer, ForeignKey('badges.id'))
)


class Account(DeclarativeBase):

    __tablename__ = 'accounts'

    id = Column(Integer, primary_key=True)
    username = Column(Unicode(25), unique=True, nullable=False)
    _password = Column('password', Unicode(128))
    email_address = Column(Unicode(50), unique=True, nullable=False)
    bio = Column(Unicode(1000), nullable=True)
    reputation = Column(Integer, default=0)
    created = Column(DateTime, default=datetime.now)

    posts = relationship('Post', backref=backref('accounts'), cascade="all, delete-orphan")
    views = relationship('View', backref=backref('accounts'), cascade="all, delete-orphan")
    votes = relationship('Vote', backref=backref('votes'), cascade="all, delete-orphan")
    badges = relationship(
        "Badge",
        secondary=association_table,
        back_populates="accounts")
    password = synonym('_password', descriptor=property(_get_password,
                                                    _set_password))



class Badge(DeclarativeBase):
    __tablename__ = 'badges'

    id = Column(Integer, primary_key=True)
    _type = Column(Enum('Gold', 'Silver', 'Bronze', name='badge_type'))
    accounts = relationship(
        "Account",
        secondary=association_table,
        back_populates="badges")

您可以在更新后使用
事件:

from sqlalchemy import event

class Account(DeclarativeBase):
    ...

def check_for_reputation(mapper, connection, target):
    # 'target' is the updated object
    if target.reputation > 500:
        # do your work here

event.listen(Account, 'after_update', check_for_reputation)