Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

python - FastAPI column products.category_id does not exist

I'm using FastAPI and I am stuck in this error while adding columns to a Model class

Here are my models

class Category(Base):
    __tablename__ = 'categories'

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, unique=True)
    description = Column(String)

    products = relationship("Product", back_populates="category")


class Product(Base):
    __tablename__ = 'products'
    
    id = Column(Integer, primary_key=True, index=True)
    category_id = Column(Integer, ForeignKey('categories.id'))
    title = Column(String, unique=True)
    price = Column(Float)
    cost = Column(Float)

    category = relationship("Category", back_populates="products")

when the API is running I got this error: sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedColumn) column products.category_id does not exist

And the problem go on, if I try to add a new attribute to Porduct model there are no changes in my database columns

There is something like run migrations in FastAPI? What I am missing?

question from:https://stackoverflow.com/questions/65929552/fastapi-column-products-category-id-does-not-exist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you will need to use something like Alembic to manage DB migrations. FastAPI does not manage this for you. Here's an example project from FastAPI that shows how to set up Alembic migrations.

https://fastapi.tiangolo.com/tutorial/sql-databases/#alembic-note

https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/alembic/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...