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.
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')
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')))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With