Python/Django Ninja

[Django Ninja] CRUD 예제 (+bulk)

yubi5050 2023. 5. 29. 16:02

CRUD - Create

- Employee 모델 객체를 생성하는 기능

- api : POST - https://127.0.0.1:8000/api/crud/employees

- body : 선언한 Schema(EmployeeIn) 

class EmployeeIn(Schema):
    name:str
    department_id: int = None
    birthdate: date = None

@router.post("/employees")
def create_employee(request, payload: EmployeeIn):
    employee = Employee.objects.create(**payload.dict())
    return {"id": employee.id}

 

CRUD - Update (PUT/PATCH)

- Employee 모델 객체를 수정하는 기능 

- api : PUT https://127.0.0.1:8000/api/crud/employees/1 (PATCH 도 가능)

- params : 특정 employee의 id

- body : 선언한 Schema(EmployeeIn) 

@router.put("/employees/{employee_id}")
def update_employee(request, employee_id: int, payload: EmployeeIn):
    employee = get_object_or_404(Employee, id=employee_id)
    for attr, value in payload.dict().items():
        setattr(employee, attr, value)
    employee.save()
    return {"success": True}

 

 

CRUD - Read (GET - Retrieve)

- Employee 모델 객체를 단일 조회 하는 기능

- api : GET https://127.0.0.1:8000/api/crud/employees/1

- params : 특정 employee의 id

- response : 선언한 Schema(EmployeeOut) 

class EmployeeOut(Schema):
    id: int
    name:str
    department_id: int = None # 없으면 Null 반환
    birthdate: date = None

@router.get("/employees/{employee_id}", response=EmployeeOut)
def get_employee(request, employee_id: int):
    employee = get_object_or_404(Employee, id=employee_id)
    return employee

 

CRUD - Read (GET - List)

- Employee 모델 객체 목록 리스트를 조회 하는 기능

- api : GET https://127.0.0.1:8000/api/crud/employees

- response : 선언한 List[ Schema(EmployeeOut) ]

@router.get("/employees", response=List[EmployeeOut])
def list_employees(request):
    qs = Employee.objects.all()
    return qs

 

CRUD - Delete (DELETE)

- Employee 모델 객체를 삭제 하는 기능

- api : GET https://127.0.0.1:8000/api/crud/employees/1

- params : 특정 employee의 id 

@router.delete("/employees/{employee_id}")
def delete_employee(request, employee_id: int):
    employee = get_object_or_404(Employee, id=employee_id)
    employee.delete()
    return {"success": True}

 

 

CRUD - Bulk Create (CREATE)

- Employee 모델 객체를 다수 생성 하는 기능

- api : POST https://127.0.0.1:8000/api/crud/bulk/employees/

- payload : List [EmployeeIn]

@router.post("/bulk/employees")
def bulk_create_employee(request, payloads: List[EmployeeIn]):
    employee_qs = [Employee(**payload.dict()) for payload in payloads]
    Employee.objects.bulk_create(employee_qs)
    return {"success": True}

 

CRUD - Bulk Update (PUT/PATCH)

- Employee 모델 객체를 다수 수정 하는 기능

- api : POST https://127.0.0.1:8000/api/crud/bulk/employees/

- payload : List [EmployeeIn]

@router.patch("/bulk-update/employees")
def bulk_update_employee(request, payloads: List[EmployeeIn]):
    employee_qs = [Employee(**payload.dict()) for payload in payloads]
    Employee.objects.bulk_update(
        objs=employee_qs, 
        fields=list(payloads[0].dict().keys()) # 변경할 fields
    )    
    return {"success": True}