Should I create mapper objects or use the declarative syntax in SQLAlchemy?

前端 未结 4 1300
北恋
北恋 2021-01-30 03:23

There are two (three, but I\'m not counting Elixir, as its not \"official\") ways to define a persisting object with SQLAlchemy:

Explicit syntax for mapper objects

4条回答
  •  余生分开走
    2021-01-30 03:36

    as of current (2019), many years later, sqlalchemy v1.3 allows a hybrid approach with the best of both worlds

    https://docs.sqlalchemy.org/en/13/orm/extensions/declarative/table_config.html#using-a-hybrid-approach-with-table

    metadata = MetaData()
    
    users_table = Table('users', metadata,
      Column('id', Integer, primary_key=True),
      Column('name', String),
    )
    
    # possibly in a different file/place the orm-declaration
    Base = declarative_base(metadata)
    
    class User(Base):
      __table__ = Base.metadata.tables['users']
      def __str__(): 
        return "" % (self.name)
    

提交回复
热议问题