Sachin
Sachin

Reputation: 3782

how to filter an object_list in django template

I have the following model:

class CompanyReport(models.Model):
    company = models.CharField(max_length=300)
    desc = models.TextField()
    text = models.TextField()
    date = models.DateTimeField()

What I want to do is to make a multilevel dropdown menu.

  1. In the first level there will be names of the company.
  2. When we click on a name there will be a list of years in which the company filed reports.
  3. When we click on a particular year, there will be a list of all the reports for that year.

When I was working in php I was able to do this using 3 different queries.

  1. The first query contained the name of the companies and the number of years they filed a report
  2. The second query contained number of reports for a particular company in a year
  3. The third query contained all the reports sorted by the company name in ascending order.

I just ran 3 nested loop, 1 for the number of companies, the other for number of years for that company and the last for the number of reports for the company in an year and then I just displayed the next report from the list.

I can do the same using Manager.raw but I am unable to iterate through the objects in the template because there is only this operation available {% for obejct in object_list %}. I need two things

  1. Way to a number based for loop
  2. An equivalent of this php $row = mysql_fetch_array($query); which simply gets the next tuple from the query list.

Output expected The kind of output I want to show is in the screenshot that I have uploaded.

Dropdown List Any sort of help is deeply appreciated.

Upvotes: 1

Views: 6626

Answers (1)

Jordan
Jordan

Reputation: 32552

I'm not sure exactly why you need the number based for loop. The normal iterator is the correct way to do a loop in Python.

If for some reason you need the index during the loop, you would use: {{forloop.counter}} for a one-indexed counter or {{forloop.counter0}} for a zero-indexed counter.

Your syntax will look something like this:

{% for company in company_list %}
    {{ company.company }}
    {% for company_year in company_year_list %}
        {% if company.date == company_year.date %} #note: this is pseudocode. you need a better comparison
            {{ company_year.date }}
            {% for company_report in company_report_list %}
                {% if company_report.company == company and company_report.year = company_year.date %}
                    {{ company_report.report }}
                {% endif %}
             {% endfor %}
         {% endif %}
     {% endfor %}
 {% endfor %}

Upvotes: 4

Related Questions