1

有必要用不同的方法创建一个儿童模型。我决定做一个元类:

class AProxy(object):
    #some methods

class BProxy(object):
    #some methods

class TestMeta(_BoundDeclarativeMeta):

    def __new__(cls, name, bases, dct):
        base = type.__new__(cls, name, bases, dct)
    if not dct.get('__tablename__'): # child create
        return base 
    prefix = name
    tablename_prefix = base.__tablename__
    children = ['A', AProxy,
                'B', BProxy]
    module = sys.modules.get(base.__module__)
    for child in children:
        n = prefix + child[0]
        b = (child[1], base)
        d = dict(__mapper_args__= dict(polymorphic_identity= tablename_prefix + child[0].lower()))
        setattr(module, n, TestMeta(n, b, d))
    return base


class Test(db.Model):
    __tablename__ = 'test'
    __metaclass__ = TestMeta
    @declared_attr
    def __mapper_args__(cls):
        return {'polymorphic_identity': '%s' % cls.__tablename__,
                'polymorphic_on': cls._type,
                'with_polymorphic': '*'}

    id = db.Column(db.Integer, primary_key= True)
    _type = db.Column(db.String(30), index= False)        
    # some columns

索引列“_type”的错误重复。如果删除索引数据库创建正常,但是当您创建子(TestA,TestB)字段时,'_type' None 会被清除。如果在获取错误时手动设置“_type”:AssertionError: No such polymorphic_identity u'testa' is defined

4

0 回答 0