简体   繁体   中英

FastAPI Models in multiple files relationship

I'm new to fastapi and I'm setting up some models to use with sqlalchemy in separate files but for some reason the one to many relationship between the two tables isn't working and the client_id column in the tasks table isn't being created at all. Below is the code for the models and also the main.py file, any help would be appreciated so I'm struggling to figure out why it's not working as most examples online have their models just in one file.

task model:

from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy.orm import relationship

from database import Base

class TaskModel(Base):
    __tablename__ = "tasks"

    id = Column(Integer, primary_key=True, index=True)
    script_log = Column(String, index=True)
    start_timestamp = Column(DateTime, index=True)
    finish_timestamp = Column(DateTime, index=True)

    client_id = Column(Integer, ForeignKey("clients.id"))
    client = relationship(
        "ClientModel", foreign_keys=[client_id], 
         back_populates="tasks"
    )

client model:

from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship

from database import Base

class ClientModel(Base):
    __tablename__ = "clients"

    id = Column(Integer, primary_key=True, index=True)
    client_name = Column(String, index=True)

    tasks = relationship(
        "TaskModel", foreign_keys="[TaskModel.client_id]", back_populates="client"
    )

main.py

from pydoc import cli
from fastapi import FastAPI

from routers import clients, processes, statuses

from database import SessionLocal, engine

from models import task, client


client.Base.metadata.create_all(bind=engine)
task.Base.metadata.create_all(bind=engine)

app = FastAPI()

app.include_router(clients.router)
app.include_router(processes.router)
app.include_router(statuses.router)

I dont get any errors when starting uvicorn and all of the other columns are showing in postgres fine except the client_id column

After changing the models you'll have to remove the existing tables, otherwise the create_all statement won't do anything (ie if the table exists, it'll just leave it - it won't update it).

To get migration support (which is what will change an existing structure into the new format), use Alembic - a project to generate migration scripts from different SQLAlchemy model versions . Add these files to your version control as any other files, and you'll be able to handle multiple versions of the same database in multiple locations as well. Run the migrations to make sure the database is up to date with your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM