Why isn't SQLAlchemy creating serial columns?

后端 未结 3 1520
一生所求
一生所求 2020-12-17 10:21

SQLAlchemy is generating, but not enabling, sequences for columns in postgresql. I suspect I may be doing something wrong in engine setup.

Using an example from the

3条回答
  •  北海茫月
    2020-12-17 10:25

    If you need to create the sequence explicitly for some reason, like setting a start value, and still want the same default value behavior as when using the Column(Integer, primary_key=True) notation, it can be accomplished with the following code:

    #!/usr/bin/env python
    
    from sqlalchemy import create_engine, Column, Integer, String, Sequence
    from sqlalchemy.ext.declarative import declarative_base
    
    Base = declarative_base()
    USER_ID_SEQ = Sequence('user_id_seq')  # define sequence explicitly
    class User(Base):
        __tablename__ = 'users'
        # use sequence in column definition, and pass .next_value() as server_default
        id = Column(Integer, USER_ID_SEQ, primary_key=True, server_default=USER_ID_SEQ.next_value())
        name = Column(String(50))
        fullname = Column(String(50))
        password = Column(String(12))
    
        def __repr__(self):
            return "" % (
                                    self.name, self.fullname, self.password)
    
    db_url = 'postgresql://localhost/serial'
    engine = create_engine(db_url, echo=True)
    Base.metadata.create_all(engine)
    

提交回复
热议问题