SQLAlchemy 有办法创建一个通用字段的父类吗

2019-03-31 21:31:14 +08:00
 whoami9894

需要创建几张表,每张表有大量通用字段,想通过继承来复用这些字段

创建了一个 metaclass 来增加类属性,但是报 metaclass conflict 了

TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

按报错需要子类的元类继承自所有父类的元类,尝试去继承 db.Model 的元类好像有点问题

代码如下

class MetaRank(type):
    def __new__(cls, name, bases, attrs):
        attrs.update({
            'id': db.Column(db.Integer),
            'rank1': db.Column(db.Integer),
            'rank2': db.Column(db.Integer),
            'rank3': db.Column(db.Integer),
            'rank4': db.Column(db.Integer),
            'rank5': db.Column(db.Integer),
            'rank6': db.Column(db.Integer),
        })
        return type.__new__(cls, name, bases, attrs)


class BaseRank(object, metaclass=MetaRank):
    pass
    
    
class MovieRank(db.Model, BaseRank):
    work_id = db.ForeignKey('movie.id')


class PhotoRank(db.Model, BaseRank):
    work_id = db.ForeignKey('photo.id')

不知道我表述清楚了没,大概意思和这篇文章一样 https://www.dreamincode.net/forums/topic/324123-metaclass-for-a-class-extending-from-sqlalchemy-declarative-base/

728 次点击
所在节点    问与答
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/550607

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX