Skip to main content
 首页 » 编程设计

python之SQLAlchemy 基于字典对约束进行建模

2025年05月04日7think

我有一张这样的 table :

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'] 
         } 

现在我想要一个约束,它允许我的样本中的颜色属性只能是对应列表中的一个项目。

哪种方法更聪明?

(我用一种 setter 方法找到的唯一方法:Using Descriptors and Hybrids)

请您参考如下方法:

您可以使用事件监听器:

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