I have three SQLAlchemy models, let's say a 'project' table, a 'worker' table and an 'equipment' table. I am using the Pydantic Schemas.
workers and equipment can be assigned to a project through Foreignkeys (i.e. worker.project_id ==project.id).
In my API end point of projects, in addition to project information, I want to give the number (count) of workers and equipment assigned to the project.
How should I do this, while I don't have a Column for these counts in my 'project' table, and hence in my Model to pass them?
class project(Base):
__tablename__ = "projects"
id = Column(Integer, primary_key=True)
name = Column(String(80), nullable=False)
site_name = Column(String(80), nullable=False)
company_id = Column(Integer, ForeignKey('companies.id'), nullable = False)
class worker(Base):
__tablename__ = "workers"
id = Column(Integer, primary_key=True)
fullname = Column(String(80), nullable=False)
project_id = Column(Integer, ForeignKey('projects.id')
class equipment(Base):
__tablename__ = "equipments"
id = Column(Integer, primary_key=True)
name = Column(String(80), nullable=False)
project_id = Column(Integer, ForeignKey('projects.id')
---------------------------------------------------------------
router = APIRouter(tags=['Projects'])
@router.get('/projects/', response_model=List[ProjectSchema])
def all_projects(db:Session=Depends(get_db)):
return project_fn.get_all(db)
-----------------------------------------------
project_fn.py
def get_all(db:Session=Depends(get_db)):
projects = db.query(project).all()
return projects
-----------------------------------------------
class ProjectSchema(BaseModel):
id: int
name: str
site_name: str = Field(min_length=3)
company: CompanyBase
class Config:
orm_mode = True
----------------------------------------------
Sample API I need:
{
"id": 1,
"name": "Project-01",
"site_name": "Site-01",
"company": {
"id": 1,
"name": "Company-01",
}
"worker_count" : 5,
"equipment_count" : 3
}
How to get 'worker_count' and 'equipment_count' here?