开发者

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开发者_如何学Python:

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.


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

Three.objects.filter(two__one=one)


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜