如何指定列的默认值应该取决于另一列的值?
说,我需要一个slug
列,默认为id
+ title
,在以下模型中:
class Page(Base):
id = Column(Integer, primary_key=True)
title = Column(String, nullable=False)
slug = Column(String, unique=True, nullable=False)
我尝试使用@validates
:
class Page(Base):
# ...
@validates('slug')
def validate(self, key, slug):
return slug or self.title # default from another column
,但是当模型构造如下时它不会触发:
Page(title='a b c')
答案 0 :(得分:1)
使用events:
@event.listens_for(Page, 'before_insert')
def page_defaults(mapper, configuration, target):
# `slug` defaults to `name`
if not target.slug:
target.slug = target.name