正如您在Stackoverflow等网站所知,当您的声誉达到特定价值或回答与特定标签相关的一定数量的问题时,您将获得徽章。如何实现?
例如,如果我想在他的声誉达到500时给用户一个徽章,我是否应该在声誉变化时检查他的声誉,看看它是否为500?
我真的不知道这个。假设这些是我的Account
和Badge
模型。
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")
答案 0 :(得分:1)
您可以使用after_update
事件:
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)