1

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.

Don
  • 16,928
  • 12
  • 63
  • 101
  • you want to access both `two` and `three` related instances from `one`? – Pannu Sep 12 '11 at 09:32
  • I'd like something like 'one.three_set.all()' to get all related Three objects – Don Sep 12 '11 at 09:49
  • any specific reason to use `one.three_set.all()` format? – Pannu Sep 12 '11 at 10:04
  • Yes, I have a framework which builds an HTML table given an instance and the name of a manager, e.g. `create_child_table(instance, manager_name)` – Don Sep 12 '11 at 10:15

2 Answers2

1

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

Three.objects.filter(two__one=one)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

You can use the reverse relationship. You can use the lower case name of the related model, in your case two and three eg:

one_tow_three = One.objects.all().values('two','two__three')
Pannu
  • 2,547
  • 2
  • 23
  • 29