class Sample(Base):
__tablename__ = 'sample'
id = Column(Integer, primary_key=True)
type = Column(Enum(u'Lion', u'Tiger', name='types'))
color = Column(Enum(... a specific list based on type ...))
和一本字典:
colors = { 'Lion' : ['gold', 'orange'],
'Tiger' : ['blackorange', 'whiteblue']
}
现在我想要一个Constraint,它允许我的Sample中的color属性只能是对应列表中的一个项目。
这是一个聪明的方法吗?
(只有我用一种setter方法找到的方法:Using Descriptors and Hybrids)
答案 0 :(得分:1)
您可以使用事件监听器:
colors = { 'Lion' : ['gold', 'orange'],
'Tiger' : ['blackorange', 'whiteblue']
}
class Sample(Base):
__tablename__ = 'sample'
id = Column(Integer, primary_key=True)
type = Column(Enum(u'Lion', u'Tiger', name='type'))
color = Column(Enum('gold', 'orange', 'blackorange', 'whiteblue', name='color'))
from sqlalchemy import event
def my_check_sample_listener(mapper, connection, target):
assert target.color in colors[target.type]
event.listen(Sample, 'before_insert', my_check_sample_listener)
event.listen(Sample, 'before_update', my_check_sample_listener)
sample = Sample(type='Tiger', color='orange')
session.add(sample)
session.commit() # Fails
sample = Sample(type='Lion', color='orange')
session.add(sample)
session.commit() # OK
sample.type = 'Tiger'
sample.color = 'whiteblue'
session.commit() # OK
sample.color = 'orange'
session.commit() # Fails