Skip to content

CRUD Sqlalchemy ORM, Pydantic and query on multiple table (like join table) #140

@tatdatpham

Description

@tatdatpham

I have trouble on making DB CRUD with two or multiple table (join table) and this is first time i working with Pydantic and FastAPI.

Sorry if my question is bullshit :'(
I have two database model

Shifdetail.py

class ShiftDetail(Base):
    id = Column(String, primary_key=True, index=True)
    shift_id = Column(String, ForeignKey("shift.id"))
    owner_id = Column(String, ForeignKey("user.id"))
    shift_date = Column(Date, nullable=False)
    create_time = Column(DateTime, nullable=False)
    shifts = relationship("Shift", back_populates="shiftdetails")
    owner = relationship("User", back_populates="shiftdetails")

User.py

class User(Base):
    id = Column(String, primary_key=True, index=True)
    email = Column(String, unique=True, index=True)
    hashed_password = Column(String)
    shiftdetails = relationship("ShiftDetail", back_populates="owner")

EXPECTED data return look like

[
  {
    "shift_id": "5240b998-7919-11ea-8f22-001a7dda7111",
    "owner_id": 56277c6c-7918-11ea-850b-001a7dda7111,
    "shift_date": "2020-04-08",
    "id": "87845423-795f-11ea-a51f-001a7dda7111",
    "create_time": "2020-04-08T13:09:39.067190",
    "owner_email": "[email protected]"
  }
]

And have ShiftDetail schema look like

class ShiftDetailBase(BaseModel):
    shift_id: Optional[str] = True
    owner_id: Optional[str] = True
    shift_date: Optional[date] = True

class ShiftDetailBaseInDB(ShiftDetailBase):
    id: str

    class Config:
        orm_mode = True

# Additional properties to return via API
class ShiftDetail(ShiftDetailBaseInDB):
    create_time: datetime
    owner_email: str

So how can write CRUD function to return datamodel ShiftDetail (with data get from joining two table ShiftDetail and User)

Because in CRUD template, i saw db_session query from self.model only :'(

def get_multi_by_owner(
        self, db_session: Session, *, owner_id: str, skip=0, limit=100
    ) -> List[ShiftDetail]:
        return (
            db_session.query(self.model)
            .filter(ShiftDetail.owner_id == owner_id)
            .offset(skip)
            .limit(limit)
            .all()
        )

And of course, i got error (ShiftDetail model dont have owner_email field like ShiftDetail schema expected

pydantic.error_wrappers.ValidationError: 1 validation error for ShiftDetail
response -> 0 -> owner_email

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions