Home > Software engineering >  How do I update a database table column? FastAPI Python
How do I update a database table column? FastAPI Python

Time:10-27

I am new to this and I have a little test database which looks like this:

class Company(Base):

    __tablename__ = 'company'

    building_id = Column(Integer, primary_key=True, nullable=False, index=True)
    name = Column(String, nullable=False)

    buildings = relationship("Building", back_populates="company")


class Building(Base):

    __tablename__ = 'building'

    building_id = Column(Integer, primary_key=True, nullable=False, index=True)
    name = Column(String, nullable=False)
    ip_address = Column(String, nullable=True)
    company_id = Column(Integer, ForeignKey('company.company_id'),nullable=False)

    company = relationship("Company", back_populates="buildings")

As you may have noticed I have messed up the name for the company id, naming it "building_id". I have changed this in the model, but it won't update the table with the error message "(sqlite3.OperationalError) no such column: company.company_id".

How do I update it?

CodePudding user response:

When you've actually launched your product you use a tool to handle database migrations for you, such as Alembic. Alembic can generate a migration script for you that runs the necessary ALTER statements to bring your database up to date with your model.

However while developing, it might be easier to just delete the .sqlite file and call create_all() again to get a fresh db created according to the schema.

  • Related