Today I Learned
bulk_create() 란?
=> Django ORM에서 제공하는 메서드. 대량의 객체를 한 번에 생성할 때 유용하게 쓰인다.
일반적으로 반복문을 사용하여 객체를 하나씩 생성하고 저장하는 것보다 훨씬 효율적으로 저장할 수 있음
order_info_list = []
order = ShopOrder.objects.create(**validated_data)
order_info = ShopOrderDetail(
order=order,
product=product,
product_count=order_quantity,
order_detail_status=0
)
order_info_list.append(order_info)
ShopOrderDetail.objects.bulk_create(order_info_list)
사용한 예시에서는
order_info_list에 ShopOrderDetail 객체를 추가하고, 마지막에 bulk_create를 이용하여 한 번에 저장시킴
이렇게 order_info_list에 있는 여러 개의 ShopOrderDetail객체를 한 번의 쿼리로 DB에 저장할 수 있음
나는 단순히 메모리와 성능의 향상 장점만 생각했는데 bulk_create()를 이용한다면 객체를 한 번에 생성하기 때문에 이 작업은 하나의 트랜잭션으로 처리되고, 데이터의 일관성과 안전성을 보장할 수 있게 되는 것도 알게되었음
'내일배움캠프 > 내일배움캠프 TIL' 카테고리의 다른 글
내일배움캠프 TIL 75일차 (0) | 2023.06.25 |
---|---|
내일배움캠프 TIL 74일차 (0) | 2023.06.25 |
내일배움캠프 TIL 72일차 (0) | 2023.06.25 |
내일배움캠프 TIL 71일차 - 코드 추가 개선 (0) | 2023.06.19 |
내일배움캠프 TIL 70일차 - 백엔드에서 페이지네이션 처리 (0) | 2023.06.19 |