Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django prefetch_related id only

Tags:

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') 
like image 914
demux Avatar asked Sep 21 '13 16:09

demux


1 Answers

Django 1.7 added Prefetch objects which let you customise the queryset used when prefetching. In this case, you'd want something like:

queryset = Contact.objects.all().prefetch_related(     Prefetch('Groups', queryset=Group.objects.all().only('id'))) 
like image 60
Freaky Dug Avatar answered Oct 01 '22 07:10

Freaky Dug