Search code examples
djangodjango-modelshierarchy

Django, querying data when we have table hierarchy


Let's consider that we have three tables in a hierarchical form:

Course 
    Topic 
        Sub-Topic 

or in code:

class Course(models.Model):
    name            = models.CharField(max_length = 100)

class Topic(models.Model):
    name            = models.CharField(max_length = 100)
    course          = models.ForeignKey('Course' , null = True , blank = True)

class SubTopic(models.Model):
    name            = models.CharField(max_length = 100)
    topic          = models.ForeignKey('Topic' , null = True , blank = True)

What I want is to get list of Courses, Topics and sub-topics to represent in a tree like Navigation system.

I know that select_related() can follow and discover ForeignKeys in any depth. How can I get use of the feature in my scenario ?


Solution

  • If you simply want to output to a template you can use _set e.g. if you passed a list of courses to your template.

    {% for c in courses %}
        {{c.name}}
        {% for t in c.topic_set.all %}
           {{t.name}}
           {% for st in t.subtopic_set.all %}
               {{st.name}}
           {% endfor %}
        {% endfor %}
    {% endfor %}