Home > Net >  Django prefetch_related fields with nested select_related fields
Django prefetch_related fields with nested select_related fields

Time:07-28

Im trying to fetch Team details with team members details also.So i prefetch_related team_member table which is linked to employee table and that is linked to User table. when i executed the code.It calls user table multiple times.Please help on this.Thanks in advance.

#query
queryset = Team.objects.prefetch_related("team_members__employee")\
            .prefetch_related("team_members__employee__user").filter(
            team_members__employee__id=employee.id)

#db call SELECT ••• FROM "leavetracker_team" INNER JOIN "leavetracker_teammember" ON ("leavetracker_team"."id" = "leavetracker_teammember"."team_id") WHERE ("leavetracker_teammember"."employee_id" = 7 AND "leavetracker_team"."id" = 16) LIMIT 21 8.00
Sel Expl
SELECT ••• FROM "leavetracker_teammember" WHERE "leavetracker_teammember"."team_id" IN (16) 0.00
Sel Expl
SELECT ••• FROM "leavetracker_employee" WHERE "leavetracker_employee"."id" IN (2, 6, 7, 10, 12) 0.00
Sel Expl
SELECT ••• FROM "core_user" WHERE "core_user"."email" IN ('[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]') 8.00
Sel Expl
SELECT ••• FROM "leavetracker_employee" LIMIT 1000 2 similar queries. Duplicated 2 times. 7.99
Sel Expl
SELECT ••• FROM "core_user" WHERE "core_user"."email" = '[email protected]' LIMIT 21 19 similar queries. Duplicated 2 times. 0.00
Sel Expl
SELECT ••• FROM "core_user" WHERE "core_user"."email" = '[email protected]' LIMIT 21 19 similar queries. Duplicated 2 times. 7.99
Sel Expl
SELECT ••• FROM "core_user" WHERE "core_user"."email" = '[email protected]' LIMIT 21 19 similar queries. Duplicated 2 times. 0.00
Sel Expl
SELECT ••• FROM "core_user" WHERE "core_user"."email" = '[email protected]' LIMIT 21 19 similar queries. Duplicated 2 times.

CodePudding user response:

To improve your prefetch, you can do select_related within TeamMember like this:

from django.db.models import Prefetch

Team.objects.prefetch_related(
    Prefetch(
        "team_members",
        queryset=TeamMembers.objects.select_related("employee__user")
    )
)
  • Related