Don
Don

Reputation: 17606

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.

Upvotes: 1

Views: 468

Answers (2)

Pannu
Pannu

Reputation: 2657

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')

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599610

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

Three.objects.filter(two__one=one)

Upvotes: 1

Related Questions