8

For example, I have models as,

class ModelBManager(models.Manager):
    def get_queryset(self):
        return self.super().get_queryset().select_related('y')

class ModelA(models.Model):
    x = models.TextField()

class ModelB(models.Model):
    y = models.ForeignKey(ModelA)
    objects = ModelBManager()

class ModelC(models.Model):
    z = models.ForeignKey(ModelB)

Now, if i do ModelC.objects.get(id=1).z i would get the ModelB instance with a prefetched ModelA instance( ModelBManager worked).

But if i do ModelC.objects.select_related('z')[0].z, there would be no prefetched ModelA instance with ModelB instance.(Basically ModelBManager did not work!)

Anyone has any idea how can i achieve this?

Thanks

r4v1
  • 355
  • 2
  • 8

1 Answers1

2

select_related allows using spans fetch deeper relationships.

In you case you should use ModelC.objects.select_related('z__y').first().z.y.

hugobessa
  • 556
  • 3
  • 10
  • Unfortunately, this does not work for me! Docs from your link states: _Base managers aren’t used when querying on related models._ Ideas? – Henhuy Jun 09 '20 at 10:29
  • If your case is similar to the one in the question you can just `ModelC.objects.select_related('z__y').first().z.y` – hugobessa Jun 10 '20 at 12:05
  • 4
    No, it's not that simple for me. In my custom manager I add multiple annotations to original queryset. Now, I want to keep those annotations through select_related() by foreign model... Don't want to add annotations over there again (DRY)... – Henhuy Jun 10 '20 at 13:46