TIL 23. Django method_set._역참조 경우

Drageon Lee·2021년 11월 21일
0

TIL_Django

목록 보기
7/8

Today's topic

👉 _set. method 사용방법

이번 post에서는 project를 진행하면서 알게된 method() 중 하나인 _set.all()에 대해서 정리해보려 한다.

👉 _set.를 사용하는 경우

query에서 B table에서 A table에 대한 F/K를 가지고 역참조를 하게 될 경우 정보를 필요로 하는 table.F/K가지고 있는 table_set.(원하는 정보)로 변수로 선언한다.

👉 예시 코드

class ProductView(View) : 
    def get(self, request, id):
        product = Product.objects.get(id=id)
        product_image = product.productimage_set.get(product_id=id)

위의 코드는 product_image table에는 product의 F/K가 있지만 product에는 따로 product_image에 대해 정보가 없는 경우이다. 이런 경우에 _set.get(id=id)나 _set.all()과 같은 method를 사용하여 역참조를 할 수 있다.

My opinion

이번 posting에서는 _set.()method를 사용하여 역참조를 할 수 있는 방법에 대해 알아 보았다. 아직 selected_related()와 prefetch_related()에 대해서 개념이 헷갈려서 다음 posting에서는 이 두 method()에 대해 정리해 봐야 겠다!

profile
운동하는 개발자

0개의 댓글