0

I have a Django application with a model A with a ManyToManyField bees to model B:

from django.db import models

class A(models.Model):
    bees = models.ManyToManyField("B", related_name="aas", blank=True)

    field1 = models.TextField()
    field2 = models.TextField()


class B(models.Model):

    field1 = models.TextField()
    field2 = models.TextField()

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?

JanKanis
  • 6,346
  • 5
  • 38
  • 42

0 Answers0