2017-11-04 125 views
0

的簡明方式,使我有很多的表與SQLAlchemy的,定義很多相似的類/表

Base = declarative_base() 

class Thing(Base): 
    __tablename__ = 'thing' 
    uid = Column(Integer, Sequence('Thing_id_seq'), primary_key=True) 
    name = Column(String) 
    def __repr__(self): 
     return "something" 

class ThingEntry(Base): 
    __tablename__ = 'thingentry' 
    uid = Column(Integer, Sequence('ThingEntry_id_seq'), primary_key=True) 
    foo = Column(Integer, ForeignKey('foo.uid')) 
    entity = Column(Integer, ForeignKey('thing')) 

class Quu(Base): 
    __tablename__ = 'quu' 
    uid = Column(Integer, Sequence('Quu_id_seq'), primary_key=True) 
    name = Column(String) 
    description = Column(String) 
    def __repr__(self): 
     return "something" 

class QuuEntry(Base): 
    __tablename__ = 'quuentry' 
    uid = Column(Integer, Sequence('QuuEntry_id_seq'), primary_key=True) 
    foo = Column(Integer, ForeignKey('foo.uid')) 
    entity = Column(Integer, ForeignKey('quu')) 

什麼是定義所有這些類/表的一些更簡潔的方式一般stucture?這種方法有很多代碼重複/自我重複。

我想某種繼承的,這樣我可以把這些代碼到

class Thing(Base): 
    pass 
class ThingEntry(Base): 
    pass 
class Quu(Base): 
    description = Column(String) 
class QuuEntry(Base): 
    pass 

具有一些特殊的自動分配其他值(__tablename__uidfoo等),但我我不確定這是可能的還是最佳的。

回答

-1

使用元類工廠的做法,因爲這樣的:

class ObjectFactory: 
    def __new__(cls, class_name, parents, attributes): 
     attributes['__tablename__'] = class_name 
     attributes['uid'] = Column(Integer, Sequence(class_name + '_id_seq'), primary_key=True) 
     attributes['name'] = Column(String) 

class EntryFactory: 
    def __new__(cls, class_name, parents, attributes): 
     attributes['__tablename__'] = class_name 
     attributes['uid'] = Column(Integer, Sequence(class_name + '_id_seq'), primary_key=True) 
     attributes['foo'] = Column(Integer, ForeignKey('foo.uid'), nullable=False) 
     attributes['entity_id'] = Column(Integer, ForeignKey(class_name[:-5]), nullable=False) 

class Thing(Base, metaclass=ObjectFactory): 
    pass 
class ThingEntry(Base, metaclass=EntryFactory): 
    pass 
class Quu(Base, metaclass=ObjectFactory): 
    description = Column(String) 
class QuuEntry(Base, metaclass=EntryFactory): 
    pass