Django multi level querying

Question:

I am using my custom created User model and I have two basic models:

class Subject(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    title = models.TextField(max_length=1000)

class Topic(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    subject = models.ForeignKey(Subject)

Is there any way (without an external package like Django-mptt) to query Topics which belong to a particular Subject and were created by a particular User? I mean when a user logs in, I want to make a list like that:

Edited: here’s the list that I want to make:

Hello user. Thank you for logging in.

Your items:

  • Subject 1

    • Topic 1
    • Topic 2
  • Subject 2

    • Topic 1

etc.

I am not sure how to do that. It might be easy but I am just a beginner.

Edit: the answer was a simple nested for loop, I am sorry for any confusion created.

Asked By: Eimantas

||

Answers:

The question is still confusing, because there is still no querying of topics or subjects going on. You are simply iterating through a user’s topics, and for each topic you are iterating through the subjects.

<ul>
  {% for topic in user.topic_set.all %}
    <li>{{ topic.title }}
      <ul>
        {% for subject in topic.subject_set.all %}
          <li>{{ subject.title }}</li>
        {% endfor %}
      </ul>
    </li>
  {% endfor %}
</ul>
Answered By: Daniel Roseman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.