[django][ORM] 모델간 Join은 어떻게 하나요?

Hyeseong·2020년 12월 29일
0

django

목록 보기
27/35

SQL에서는 JOIN을 이용해서 동일한 값을 가진 column(field)을 기준으로 두 table을 합칠수 있어요.

a1 = Article.objects.select_related('reporter')
a1
<QuerySet [<Article: International News>, <Article: Local News>, <Article: Morning news>, <Article: Prime time>, <Article: Test Article>, <Article: Weather Report>]>

print(a1.query)
SELECT "events_article"."id", "events_article"."headline", "events_article"."pub_date", "events_article"."reporter_id", "events_article"."slug", "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "events_article" INNER JOIN "auth_user" ON ("events_article"."reporter_id" = "auth_user"."id") ORDER BY "events_article"."headline" ASC

 a2 = Article.objects.filter(reporter__username='John')
 a2
 <QuerySet [<Article: International News>, <Article: Local News>, <Article: Prime time>, <Article: Test Article>, <Article: Weather Report>]>
 
print(a2.query)
SELECT "events_article"."id", "events_article"."headline", "events_article"."pub_date", "events_article"."reporter_id", "events_article"."slug" FROM "events_article" INNER JOIN "auth_user" ON ("events_article"."reporter_id" = "auth_user"."id") WHERE "auth_user"."username" = John ORDER BY "events_article"."headline" ASC
profile
어제보다 오늘 그리고 오늘 보다 내일...

0개의 댓글