Strange prefetch_related Issue. Is this a bug?

46 views
Skip to first unread message

Lyle Pratt

unread,
Jul 9, 2015, 8:05:28 AM7/9/15
to django...@googlegroups.com
I have a strange issue where prefetch_related sometimes fails to populate related objects when using Proxy models. I believe it is a bug, but I'd like some second opinions on what might be going on.


Here is my example filter:
my_filter = Activity.objects.all().prefetch_related("recording_set")

If the first item in the queryset is of a certain proxy model (in the example below, "sms"), no prefetched objects are populated. In other words, if the first item has "activity=sms" (and not "activity=call") then no "recordings" are populated in ANY of the queryset items returned.

Here are my example models:

class Activity(models.Model):
    activity = models.CharField(max_length=20, choices=ACTIVITY_CHOICES, default='call')

class CallManager(models.Manager):
    def get_queryset(self):
        return super(CallManager, self).get_queryset().filter(activity='call')

class Call(Activity):
    def __init__(self, *args, **kwargs):
        self._meta.get_field('activity').default = "call"
        super(Call, self).__init__(*args, **kwargs)

    class Meta:
        proxy = True
    objects = CallManager()


class SmsManager(models.Manager):
    def get_queryset(self):
        return super(SmsManager, self).get_queryset().filter(activity='sms')

class Sms(Activity):
    
    def __init__(self, *args, **kwargs):
        self._meta.get_field('activity').default = "sms"
        super(Sms, self).__init__(*args, **kwargs)

    class Meta:
        proxy = True
    objects = SmsManager()

class Recording(models.Model):
    sms = models.ForeignKey("Sms", null=True, blank=True)
    call = models.ForeignKey("Call", null=True, blank=True)

Lyle Pratt

unread,
Jul 9, 2015, 8:36:06 AM7/9/15
to django...@googlegroups.com

It appears that the issue is because if the first item in the list is of a type "sms", then prefetch_related looks up the related items using the "sms_id" foreign key. How can I get around this? Is there a way to specify the column that prefetch_related should use for look ups?
Reply all
Reply to author
Forward
0 new messages