본문 바로가기

Python

[SQLAlchemy] schema에 따라 객체 변형해서 담기

반응형

router

한땀한땀 넣기

# router

# 별로 없을때, 한땀한땀 넣기
@router.get("/{report_id}", response_model=schemas.Report)
def report_read(report_id:int):
	report = (db.query(models.report, models.user.name.label("writer"))
                .join(models.user, models.report.writer == models.id)
                .first())
    return schemas.test(
        id=report.id,
        title=report.name,
        contents=report.contents,
        comment=schemas.childComment.from_orm(report.comment),
    )

jsonable_encoder 사용하기

*주의* orm으로 객체를 넣고 싶을 경우 안된다. 그래서 추가로 넣어줘야한다.
# router
from fastapi.encoders import jsonable_encoder

# 많을 때 jsonable_encoder 사용하기
@router.get("/{report_id}", response_model=schemas.Report)
def report_read(report_id:int):
	report = (db.query(models.report, models.user.name.label("writer"))
                .join(models.user, models.report.writer == models.id)
                .first())
                
    report_dict = jsonable_encoder(report[0])
    report_dict["writer"] = report.writer
    # 자동 orm 이 안먹혀서 이렇게 추가로 넣어줘야한다.
    report_dict["comments"] = report[0].comments
    return report_dict

models

# models
class User(Base):
  __tablename__ = 'user'
  __table_args__ = {'comment': '사용자'}
  id = Column(INTEGER, primary_key=True, autoincrement=True)
  name = Column(INTEGER(unsigned=True), nullable=False, comment='사용자명')

class Report(Base):
  __tablename__ = 'report'
  __table_args__ = {'comment': '보고서'}
  
  id = Column(INTEGER, primary_key=True, autoincrement=True)
  write = Column(INTEGER(unsigned=True), ForeignKey('user.id'), nullable=False, comment='작성자')
  title = Column(String(50), nullable=True, comment='제목')
  contents = Column(String(255), nullable=True, comment='내용')
  
  comments = relationship("Comments", backref=backref('report'))

class Comments(Base):
  __tablename__ = 'comments'
  __table_args__ = {'comment': '코멘트'}
  
  id = Column(INTEGER, primary_key=True, autoincrement=True)
  report_id = Column(INTEGER(unsigned=True), ForeignKey('report.id'), nullable=False)
  contents = Column(String(255), nullable=True, comment='내용')
  
  report = relationship("Report", backref=backref('comments'))

schemas

# schemas
from pydantic import BaseModel
class User(BaseModel):
    id: int
    name: str

class Comments(BaseModel):
    id: int
    contents: str

class Report(BaseModel):
    id: int
    write_name: str
    title: str
    contents: str
    comments: List[Comments]
    
    class Config:
        orm_mode = True

 

반응형