๐Ÿ’˜ Select_related & Prefetch_related

Min-Ho Leeยท2020๋…„ 7์›” 26์ผ
0

Learn Django

๋ชฉ๋ก ๋ณด๊ธฐ
6/13
post-thumbnail

Sunday_July_26
.
.
.
์‚ฌ์‹ค ์ด ๊ธ€์„ ์“ด ๊ณ„๊ธฐ๊ฐ€ ์žˆ๋‹ค.

์ผ๋‹จ ๊ณต์‹๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•ด์„œ ๊ณต๋ถ€๋ฅผ ํ•œ ํ›„, ๊ฐ„๋‹จํ•˜๊ฒŒ ๋‚ด์šฉ์„ ๋‹ค๋ฃจ๊ณ 
์ด ๊ธ€์„ ์“ด ๋ชฉ์ ์„ ์–˜๊ธฐ ํ•ด๋ณด๋ ค๊ณ  ํ•œ๋‹ค.

select_related / prefetch_related์— ๊ด€ํ•œ Django ๊ณต์‹ ๋ฌธ์„œ

select_related

์ •์ฐธ์กฐ ๊ด€๊ณ„์—์„œ ์‚ฌ์šฉ๋œ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด Main Category๊ฐ€ ์žˆ๊ณ  Sub Category๊ฐ€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ณด์ž.
Sub์€ Main์„ ์ฐธ์กฐํ•œ๋‹ค.

prefetch_related

select_related์™€ ๋‹ค๋ฅด๊ฒŒ MTO or MTM ์—ญ์ฐธ์กฐ ๊ด€๊ณ„์—์„œ ๋ณ„๋„์˜ 2๊ฐœ์˜ ์ฟผ๋ฆฌ๋ฅผ ์ˆ˜ํ–‰ํ•œ๋‹ค.
(๊ทธ ํ›„ ํŒŒ์ด์ฌ์ด ์กฐ์ธ์„ ํ•œ๋‹ค.)

๊ทธ๋Ÿฐ๋ฐ ์—ฌ๊ธฐ์„œ ๋‚ด๊ฐ€ ๊ถ๊ธˆํ–ˆ๋˜ ์ ์€, prefetch๋ฅผ ์“ธ ๋•Œ ์˜€๋‹ค.

MTM์—์„œ a, b, ์ค‘๊ฐ„ํ…Œ์ด๋ธ”์„ inter๋ผ ํ–ˆ์„๋•Œ,
inter๋Š” a์™€ b๋ฅผ ์ฐธ์กฐํ•  ๊ฒƒ์ด๋‹ค.

๊ทธ๋Ÿฐ๋ฐ a์—์„œ b๋ฅผ ๊ฑด๋„ˆ๊ฑด๋„ˆ ์ฐธ์กฐํ•ด์•ผ๋งŒ ํ•˜๋Š”์ค„ ์•Œ์•˜๋‹ค.

ํ•˜์ง€๋งŒ ํ•œ๋ฒˆ์— a์—์„œ b๋ฅผ ์ฐธ์กฐํ•˜๋Š” ๊ฒƒ์ด ๊ฐ€๋Šฅํ–ˆ๋‹ค.

profile
๐Ÿ‡ Rabbit can take a rest, but ๐Ÿข turtle can't

0๊ฐœ์˜ ๋Œ“๊ธ€