Django select_related the join table only for a many-to-many relation
I have a Django application with a model A
with a ManyToManyField
bees
to model B
. For one view, when I select a bunch of A's I also need the ids of their B's. The default where Django queries the related B's for each A individually is too slow, so I use select_related
.
If I do A.objects.select_related('bees')
Django selects the full B
models:
SELECT ("app_a_bees"."from_a_id") AS "_prefetch_related_val_from_a_id",
"app_b"."id",
"app_b"."field1",
"app_b"."field2",
...
FROM "app_b"
INNER JOIN "app_a_bees" ON ("app_b"."id" = "app_a_bees"."to_b_id")
WHERE "app_a_bees"."from_a_id" IN (... list of A ids ...)
But I only need their id values, so I only need to select the app_a_bees
join table to get them, not the B
model table.
I tried A.objects.select_related('bees__id')
(I also tries 'bees_id'
) but Django doesn't like that, individual fields cannot be prefetched in this way.
I have also tried A.objects.select_related(Prefetch("bees", queryset=B.objects.all().only("id"))
, but that still joins to the B
table to select the id
field, which Django already has from the join table.
Is there any way to prefetch just the join table for my A
objects?