[Solved]-Multiple fields to the same DB column


It looks like a bug or oversight in django. As a workaround, you can try defining a custom manager which does a 2-stage prefetching.

from django.db import models
from django.db.models import Q
from django.contrib.contenttypes.models import ContentType

class PrefetchWorkaroundManager(models.Manager):
    def get_queryset(self):
        q = super(PrefetchWorkaroundManager, self).get_queryset()
        content_typeA = ContentType.objects.get_for_model(ModelA)
        content_typeB = ContentType.objects.get_for_model(ModelB)
        return q.filter(content_type__pk = content_typeA.id).prefetch_related('content_object', 'content_object__event_object') | \
               q.filter(content_type__pk = content_typeB.id).prefetch_related('content_object', 'content_object__event')

class ModelC(models.Model):

    objects_prefetched = PrefetchWorkaroundManager()

Each caller which wants prefetching to take place should access ModelC.objects_prefetched instead of ModelC.objects:


I admit, I didn’t test it, so it probably doesn’t work as-is. But I believe this approach is sound.


Leave a comment