Custom RelatedManager?

20 views
Skip to first unread message

Erik Cederstrand

unread,
May 22, 2015, 4:26:01 AM5/22/15
to Django Users
Hi folks,


I have some models with a custom Manager that prefetches certain fields:

class PrefetchManager(models.Manager):
def get_queryset(self):
return super().get_queryset()\
.select_related(*self.model.select_fields)\
.prefetch_related(*self.model.prefetch_fields)


class MyModel(models.Model):
foo = models.ForeignKey(Foo)
bars = models.ManyToManyField(Bar, related_name='mymodels')

select_fields = ('foo',)
prefetch_fields = ('bars')
prefetched = PrefetchManager()


This allows the nice and succinct "MyModel.prefetched.filter(...)" to get model instances with prefetched fields. However, I would also like this to work with RelatedManager, i.e.:

m = MyModel.objects.get(pk=1)
m.bars.prefetched.filter(...)

to get all Bar connected to m with the prefetched fields I have defined on Bar. Is there a way to do this? Can I create a custom RelatedManager for 'bars'? I can rewrite it as:

Bar.prefetched.filter(mymodels=m, ...)

but it feels more awkward.

Thanks,
Erik
Reply all
Reply to author
Forward
0 new messages