๐ŸŒˆ select related& prefetch related

may_soouuยท2020๋…„ 10์›” 1์ผ
1

Django-ORM

๋ชฉ๋ก ๋ณด๊ธฐ
4/5

select related ์™€ prefetch related๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ฟผ๋ฆฌ๋ฅผ ์ค„์—ฌ์„œ ์ตœ์ ํ™” ํ•  ์ˆ˜ ์žˆ๋‹ค.
์ฆ‰, ํ•˜๋‚˜์˜ QuerySet ๊ฐ์ฒด๋ฅผ ๊ฐ€์ ธ์˜ฌ ๋•Œ ์—ฐ๊ด€์žˆ๋Š” Modele๋“ค์„ ๊ฐ™์ด ๊ฐ€์ ธ์˜จ๋‹ค

์šฐ์„  ๊ฐ„๋‹จํ•œ ๋ชจ๋ธ ํ•˜๋‚˜๋กœ ์˜ˆ๋ฅผ ๋“ค์–ด ์ดํ•ดํ•ด๋ณด์ž.

models.py
-------------
# ๊ณ ๊ฐ ์„œ๋กœ๊ฐ€ ๊ตฌ๋งคํ•œ ๋ฌผ๊ฑด์€ ์ ˆ๋Œ€ ๊ฒน์น˜์ง€ ์•Š๋Š”๋‹ค๋Š” ๊ฐ€์ •ํ•˜์—, ๊ณ ๊ฐ๊ณผ ๊ทธ ๊ณ ๊ฐ์ด ๊ตฌ๋งคํ•œ ๋ฌผํ’ˆ์˜ ๊ด€๊ณ„๋กœ ์ƒ๊ฐํ•ด๋ณด์ž
# (์ผ๋Œ€๋‹ค์˜ ๊ด€๊ณ„)

from django.db import models

class Customer(models.Model):
   name = models.CharField(max_length=20)

class Products(models.Model):
   name  = models.CharField(max_lenght=50)
   buyer = models.ForeignKey(Customer, on_delete=models.CASCADE)

select_related๋Š” 1:1 ํ˜น์€ 1:N์˜ ๊ด€๊ณ„์—์„œ N์˜ ์ž…์žฅ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ์œ„์˜ ๊ฒฝ์šฐ, 1:N์˜ ๊ด€๊ณ„์ด๋ฉด์„œ N์˜ ์ž…์žฅ์ธ Products์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค

N์˜ ์ž…์žฅ
: ๊ณ ๊ฐ 1๋ช…์ด ๋ฌผ๊ฑด ์—ฌ๋Ÿฌ๊ฐœ๋ฅผ ์ƒ€์œผ๋‹ˆ๊นŒ N์— ํ•ด๋‹นํ•˜๋Š” ๊ฒƒ์€ Products

buy_product = Products.objects.select_related('buyer').get(id=1)

foreign key๋กœ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋Š” buyer์นผ๋Ÿผ์„ ๋™์‹œ์— ๋ถˆ๋Ÿฌ์˜ด์œผ๋กœ์จ ์ฟผ๋ฆฌ๋ฌธ ๊ฐฏ์ˆ˜๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.

prefetch_related๋Š” M:M ํ˜น์€ 1:N์˜ ๊ด€๊ณ„์—์„œ 1์˜ ์ž…์žฅ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

์œ„์˜ ๊ฒฝ์šฐ, ํ•œ๋ช…์˜ customer๊ฐ€ ๊ตฌ๋งคํ•œ ์ƒํ’ˆ์„ ์ „๋ถ€ ๋ถˆ๋Ÿฌ์˜ค๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

product_list = Customer.objects.prefetch_related('products_set').get(id=1)

์—ญ์ฐธ์กฐ์˜ ๊ฒฝ์šฐ _set ์„ ์“ด๋‹ค.
๋งŒ์•ฝ์— ์ฐธ์กฐํ•˜๋Š” ๋ชจ๋ธ์—์„œ related_name์„ ๋”ฐ๋กœ ์ผ๋‹ค๋ฉด ๊ทธ ์ด๋ฆ„์„ ์“ฐ๋ฉด ๋œ๋‹ค.

ex.
class ProductRelated(models.Model):
	product          = models.ForeignKey(Products, on_delete=models.CASCADE, related_name='product')
	related_product  = models.ForeignKey(Products, on_delete=models.CASCADE, related_name ='related_product')
    
์ด๋ ‡๊ฒŒ related_name์„ ๋”ฐ๋กœ ๋ช…์‹œํ–ˆ๋‹ค๋ฉด ์—ญ์ฐธ์กฐ์‹œ _set์„ ์“ฐ์ง€ ์•Š๋Š”๋‹ค.
  • ์—ญ์ฐธ์กฐ๋ž€?
    ForeinKey์— ์˜ํ•ด ์ฐธ์กฐ๋˜๊ณ ์žˆ๋Š” ๋ชจ๋ธ์—์„œ ์ฐธ์กฐํ•˜๋Š” ๋ชจ๋ธ์„
    ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ.
profile
back-end ๊ฐœ๋ฐœ์ž

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