djangodjango-modelsdjango-queryset

django prefetch_related id only


I'm trying to optimise my queries but prefetch_related insists on joining the tables and selecting all the fields even though I only need the list of ids from the relations table.

queries

You can ignore the 4th query. It's not related to the question.

Related Code:

class Contact(models.Model):
    ...
    Groups = models.ManyToManyField(ContactGroup, related_name='contacts')
    ...

queryset = Contact.objects.all().prefetch_related('Groups')

Solution

  • Django 1.7 added Prefetch objects which let you customise the queryset used when prefetching.

    In particular, see only().

    In this case, you'd want something like:

    queryset = Contact.objects.all().prefetch_related(
        Prefetch('Groups', queryset=Group.objects.all().only('id')))