SQLAlchemy,定义许多类似类/表的简明方法

时间:2017-11-04 00:18:49

标签: python database oop sqlalchemy

所以我有很多具有

结构的表格
class Thing(Base):
    pass
class ThingEntry(Base):
    pass
class Quu(Base):
    description = Column(String)
class QuuEntry(Base):
    pass

有哪些更简洁的方法来定义所有这些类/表?这种方法有很多代码重复/自我重复。

我正在考虑某种继承,以便我可以将代码转移到

__tablename__

使用某些魔法自动分配其他值(uidfoo<ng-template #defaultTabButtons> <div class="default-tab-buttons"> This is really a massive template so I want to be in a separate static HTML file </div> </ng-template> <ng-container *ngTemplateOutlet="myTemplate"> </ng-container> 等),但我不确定这是否可行或最佳。

2 个答案:

答案 0 :(得分:0)

您应该查看有关自动反映http://docs.sqlalchemy.org/en/rel_1_1/core/reflection.html

的文档

答案 1 :(得分:-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