SQLAlchemy: avoiding repetition in declarative style class definition

后端 未结 3 685
谎友^
谎友^ 2021-02-05 21:48

I\'m using SQLAlchemy, and many classes in my object model have the same two attributes: id and (integer & primary key), and name (a string). I\'m trying to avoid declaring

3条回答
  •  别跟我提以往
    2021-02-05 22:29

    I think I got it to work.

    I created a metaclass that derives from DeclarativeMeta, and made that the metaclass of C1 and C2. In that new metaclass, I simply said

    def __new__(mcs, name, base, attr):
      attr['__tablename__'] = name.lower()
      attr['id'] = Column(Integer, primary_key = True)
      attr['name'] = Column(String)
      return super().__new__(mcs, name, base, attr)
    

    And it seems to work fine.

提交回复
热议问题