결론부터 말하자면
참조하는 모델(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는 정말 간단하게 많은 기능을 구현하고 있었다...
https://stackoverflow.com/questions/40667414/prefetch-related-foreignkey-reverse-lookup-in-django
공교롭게 방법을 찾고 난 뒤에, stackoverflow에서 똑같은 형태의 코드를 발견... 검증을 받았다 생각한다.
'Programming > Django' 카테고리의 다른 글
[DRF] 귀찮은건 싫어! ViewSet 사용해보기 (0) | 2021.11.21 |
---|---|
[DRF] Serializer로 역참조의 역참조 모델 가져오기 (0) | 2021.10.22 |
[Django, Docker] gunicorn에 vscode debugger 붙이기 (0) | 2021.10.20 |
[DRF] get_queryset에서 벗어나기(get 사용) (0) | 2021.10.15 |
postgres에 django를 활용해 csv 업로드 하기 (0) | 2021.09.29 |