Custom metaclass to create hybrid properties in SQLAlchemy

霸气de小男生 提交于 2019-12-04 17:41:25

There's no need to use metaclasses for a SQLAlchemy mapped class as we supply plenty of events to add features to classes as they are created and/or mapped. mapper_configured might be good here, which if you're on 0.8 you can apply to MyBase directly:

@event.listens_for(MyBase, 'mapper_configured')
def get_special_columns(mapper, cls):
    for attrname in dir(cls):
        val = getattr(cls, attrname)
        if isinstance(val, SpecialColumn):
             name1, name2 = "_%s_1" % attrname, "_%s_2" % attrname
             setattr(cls, name1, Column(...))
             setattr(cls, name2, Column(...))

             @hybrid_property
             def myhybrid(self):
                 return getattr(self, name1), getattr(self, name2)

             @myhybrid.setter
             def myhybrid(self, value):
                 setattr(self, name1, value[0])
                 setattr(self, name2, value[1])

             setattr(cls, attrname, myhybrid)

note that setattr() is the best way to go here, simple and to the point.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!