Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fastapi orm #102

Open
yeomko22 opened this issue Sep 16, 2021 · 3 comments
Open

fastapi orm #102

yeomko22 opened this issue Sep 16, 2021 · 3 comments

Comments

@yeomko22
Copy link
Owner

ORM

  • fastapi도 마찬가지로 sqlalchemy와 같은 ORM을 사용한다.
  • pydantic은 어디까지나 data validation을 담당한다. 이는 ORM을 대체할 수 없다.
  • 따라서 fastapi 프로젝트를 진행할 때에는 ORM model 파일과 pydantic 스키마 파일을 별도로 만들어주어야한다.
@yeomko22
Copy link
Owner Author

class User(UserBase):
    id: int
    is_active: bool
    items: List[Item] = []

    class Config:
        orm_mode = True
  • pydantic model에 Config 클래스 안에 orm_mode를 True로 설정한다.
  • 이를 통해서 pydantic model이 orm model과 compatible하다.

@yeomko22
Copy link
Owner Author

CRUD 예시

from sqlalchemy.orm import Session

from . import models, schemas


def get_user(db: Session, user_id: int):
    return db.query(models.User).filter(models.User.id == user_id).first()


def get_user_by_email(db: Session, email: str):
    return db.query(models.User).filter(models.User.email == email).first()


def get_users(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.User).offset(skip).limit(limit).all()


def create_user(db: Session, user: schemas.UserCreate):
    fake_hashed_password = user.password + "notreallyhashed"
    db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


def get_items(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.Item).offset(skip).limit(limit).all()


def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):
    db_item = models.Item(**item.dict(), owner_id=user_id)
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    return db_item
  • 들어오는 데이터의 타입 검사는 pydantic이 수행

@yeomko22
Copy link
Owner Author

from .database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)
  • main.py에서는 이렇게 engine과 model을 import 해주어서 사용한다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant