Programming/Django

Django foreign key를 사용했을 때 역참조(DRF)

stein 2021. 10. 15. 11:04

결론부터 말하자면

참조하는 모델(ohlcv)과 참조되는 모델(share_announce)가 있을 때,
참조되는 모델.참조하는모델_set으로 접근가능하다. 이때, 참조하는 모델 foreign key 설정시 related_name을 설정해주면 해당 이름으로 접근할 수 있다.(필자는 ohlcv로 설정)

그러니까.. django가 알아서 해준다.

 

구글링을 했을 때, 정참조를 할 때는 select_related를 역참조를 할 때는 prefetch_related를 쓰라는 얘기를 보았다.

하지만 두 방식 모두 cache에 미리 담아둬서, db에 한 번 더 쿼리를 보내지 않게 해주도록 support하는 역할이지, 해당 function을 쓴다고 해서 return되는 query_set에 해당 내용이 담겨져있는게 아니다.

 

https://docs.djangoproject.com/en/3.2/ref/models/querysets/#select-related

This is a performance booster which results in a single more complex query but means later use of foreign-key relationships won’t require database queries.

 

prefetch_related('참조모델_set') (또는 related_name을 모델에서 선언해 주든지)는 참조모델을 매번 참조하지 않을 수 있도록 cache에 넣어준다.

https://docs.djangoproject.com/en/3.2/ref/models/querysets/#prefetch-related

now each time self.toppings.all() is called, instead of having to go to the database for the items, it will find them in a prefetched QuerySet cache that was populated in a single query.

필자가 사용한 방법

여기서 계속 헷갈렸던 점은, prefetch_related를 붙여주었는데 share_announces에 ohlcv관련 값이 없던 것이었다.

결국 그 원인은 serializer에서 구현됐었던 기능인데, query_set이 만들어낸다고 생각했던게 문제였다.

serializer는 정말 간단하게 많은 기능을 구현하고 있었다...

serializer를 붙여주고, many=True만 붙여주니 알아서 foreign key를 타고 역참조를 깔끔하게 해온다;;

https://stackoverflow.com/questions/40667414/prefetch-related-foreignkey-reverse-lookup-in-django

 

prefetch_related() ForeignKey reverse lookup in Django?

I've got two models: class Company(models.Model): ... class Supplier(models.Model): company = models.ForeignKey(Company, null=True, related_name="suppliers") How to get all Companies with ...

stackoverflow.com

공교롭게 방법을 찾고 난 뒤에, stackoverflow에서 똑같은 형태의 코드를 발견... 검증을 받았다 생각한다.