meteorainer
meteorainer

Reputation: 952

Fetching related parent objects in a chain in Django

As always, please forgive my ignorance. I promise I searched first.

Ive got my Django views put together for my employee class. One of the properties is the report_to field. This field is populated by a FK to another user obj.

My task now is to build a command tree. So I need a list of A reports to B reports to C reports to D all the way up the chain.

At first I thought is this would end up being a looped queury, but there has to be a better solution.

Prefetch_related maybe? Or select_related?

How do I get this to grab all the relations until it reaches ceo and reports_to is null?

Upvotes: 1

Views: 263

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600051

What you have there is a tree structure, with the CEO at the top. Those aren't easy to represent in databases generally. Luckily there is a nice algorithm that will do it for you, MPTT, and a great Django implementation in django-mptt. It will involve some changes to your data, but using that will allow you to get all ancestors of an employee - or all descendants - in one go.

Upvotes: 2

Related Questions