This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
queryset = ( | |
AModel.objects. | |
.prefetch_related( | |
"b_model_set", | |
"c_models", | |
) | |
) | |
# 위 쿼리셋과 아래 쿼리셋은 동일한 SQL을 수행한다 | |
from django.db.models import Prefetch |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
order_list = ( | |
Order.objects | |
.select_related('order_owner') | |
.filter(order_owner__username='username4') | |
.prefetch_related('product_set_included_order') | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT "orm_practice_app_order"."id", | |
"orm_practice_app_order"."reg_date", | |
".... 생략", | |
"orm_practice_app_user"."username", | |
"orm_practice_app_user"."first_name", | |
"orm_practice_app_user"."last_name", | |
"orm_practice_app_user"."email", | |
".... 생략", | |
"orm_practice_app_user"."userinfo_id", | |
"orm_practice_app_user"."aab_id" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db.model.sql import Query # Query()는 개발자가 정의한 QuerySet을 읽어서 실제 SQL을 생성해주는 구현체다 | |
class QuerySet: | |
query: Query = Query() # 이것을 나는 메인쿼리 라고 명명한다. | |
_result_cache: List[Dict[Any,Any]] = dict() # SQL의 수행결과를 여기 저장해놓고 재사용한다 (QuerySet Cache) | |
# QuerySet 재호출시 이 프로퍼티에 저장된 데이터가 없으면 SQL을 호출해서 데이터를 가져온다. | |
_prefetch_related_lookups: Tuple[str] = () # prefetch_related(여기선언된 값들) 을 이 프로퍼티에 저장함 | |
# 이것을 나는 추가쿼리(셋)이라고 명명한다. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 메인 쿼리와 추가쿼리셋이 무엇인지 설명하는 예제 | |
queryset = (Model.objects. | |
.annotate(zzz=F('블라블라_필드')) | |
.select_related('aaa', 'bbb', 'ccc') | |
.filter(~~~메인쿼리에_걸리는_조건절~~~) # 여기 까지가 메인쿼리에 영향을 주는 옵션들이다. | |
.prefetch_related('qqq', 'www', 'eee') # 여기 선언된 3개의 역참조필드를 조회하기위해 3개의 추가쿼리(셋)이 생성된다. | |
) | |
""" | |
위 queryset 호출시 발생하는 SQL |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
values_list_queryset = list(User.objects.filter(id=1).values_list('id', 'username', 'is_superuser', named=True)) | |
# 위에 선언해준 애트리뷰트들만 Raw라는 객체에 담아서 반환해준다 | |
[Row(username='username1', id=1, is_superuser=False)] | |
# 모델자체가 무거우면 이렇게 필요한 프로퍼티들만 가진 객체를 반환받는것도 깔끔 | |
# 좋은 기능이다! | |
values_list_queryset[0].username # 'username1' | |
values_list_queryset[0].is_superuser # False |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--------------- | |
# ModelIterable 인 경우 객체 반환 (문제없음) | |
qqq = list(User.objects.prefetch_related('user_permissions').filter(id=1)) | |
""" | |
# 메인쿼리 | |
SELECT * FROM `auth_user` WHERE `auth_user`.`id` = 1; | |
# 추가 쿼리(셋) | |
SELECT * |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gg= list(Product.objects.select_related('product_owned_company').filter(id=1).values()) | |
(0.002) SELECT `orm_practice_app_product`.`id`, `orm_practice_app_product`.`name`, | |
`orm_practice_app_product`.`price`, `orm_practice_app_product`.`product_owned_company_id` | |
FROM `orm_practice_app_product` | |
WHERE `orm_practice_app_product`.`id` = 1; | |
# .select_related('product_owned_company') 를 무시하고 JOIN 하지 않는다... | |
# 그리고 raw단위로 데이터를 가져와서 product_owned_company객체 대신 foreignKey pk를 가져옴 | |
[{'id': 1, 'name': 'product_name1', 'price': 94772, 'product_owned_company_id': 40}] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ModelIterable | |
result : List[Model] = Model.objects.all() | |
.only() # 지정한 필드만 조회 | |
.defer() # 지정한 필드를 제외하고 조회 | |
# ValuesIterable | |
result : List[Dict[str,Any]] = Model.objects.valeus() | |
# ValuesListIterable | |
result : List[Tuple[str,Any]] = Model.objects.values_list() | |