SQLAlchemy: avoiding repetition in declarative style class definition

后端 未结 3 625
谎友^
谎友^ 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:55

    Could you also use the Column's copy method? This way, fields can be defined independently of tables, and those fields that are reused are just field.copy()-ed.

    id = Column(Integer, primary_key = True)
    name = Column(String)
    
    class C1(declarative_base()):
        id = id.copy()
        name = name.copy()
        #...
    
    class C2(declarative_base()):
        id = id.copy()
        name = name.copy()
        #...
    

提交回复
热议问题