Search code examples
djangodjango-custom-managerdjango-related-manager

Django: two-step RelatedManager


I have three models linked by foreign keys:

class One(models.Model):
    ...

class Two(models.Model):
    one = models.ForeignKey(One)

class Three(models.Model):
    two = models.ForeignKey(Two)

and I can do:

one.two_set.all()

to access all related 'Two' instances from a 'One' instance.

How can I build a custom manager to access all 'Three' instances from a 'One' instance?

I need this because I have a framework which builds an HTML table given an instance and one of its managers:

create_child_table(instance, manager_name)

so, it would be fine if I can have a 'three_set' manager to be used on the instance.

SOLUTION I ended up by adding a ForeignKey from Three to One. Thanks to your answers that reminded me of the KISS philosophy.


Solution

  • You don't need a manager. This will do it:

    Three.objects.filter(two__one=one)