Home > Software engineering >  Postgres auto incrementing ID of int type
Postgres auto incrementing ID of int type

Time:10-15

I am learning fastapi and I've created a model in models.py as follows:

class Post(Base):
    __tablename__ = "posts"

    id = Column(Integer, primary_key=True, nullable=False)
    title = Column(String, nullable=False)
    content = Column(String, nullable=False)
    published = Column(Boolean, server_default='TRUE')
    created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text('now()'))

I have mentioned id as int but it is auto incrementing like serial and also serial is automatically set to default. Even if I am passing id from postman it is still getting auto incremented and discarding my sent value.

CodePudding user response:

You have to explicitly disable the autoincrement functionality - an integer primary key without a default value will usually have autoincrement functionality added automagically:

The default value is the string "auto", which indicates that a single-column (i.e. non-composite) primary key that is of an INTEGER type with no other client-side or server-side default constructs indicated should receive auto increment semantics automatically.

Instead, set the autoincrement argument explicitly to False:

False (this column should never have auto-increment semantics)

  • Related