从列表列表中创建django中的表

时间:2016-05-26 11:09:46

标签: python django python-3.x python-3.5 django-1.9

所以,我正在尝试制作一个看起来像这样的表:

Thing/Person | PersonA                    | PersonB
ThingA       | [green]PersonA[/green]     | [red]PersonB[/red]
ThingB       | [red]PersonA[/red]         | [green]PersonB[/green]

每个“人”都有一个指向“东西”的主键,“Person.thing”。如果一个人与多个事物有关,则在数据库中有多个具有相同.name值的条目。在视图中,我注意制作一个列表列表,其中包含该人名的html颜色版本。如果他们有关系则为绿色,如果他们没有关系则为红色:

persons_list = Persons.objects.all()
context_dict["persons"] = persons_list

persons_list_nodups = Persons.objects.values_list('name', flat=True).distinct()
context_dict["persons_nodups"] = persons_list_nodups

things_list = Things.objects.order_by("-title")
context_dict["things"] = things_list

listOfRelationsToThings = []

a = ""
b = ""
c = []
lineyes = '<font color="green">  </font>'
lineno = '<font color="red">  </font>'
indexyes = lineyes.find(" </font>")
indexno = lineno.find(" </font>")
i = 0
number_of_persons = len(persons_list_nodups)
for thing in things_list:
    for person in persons_list_nodups:
        if i == len(persons_list_nodups):
            listOfRelationsToThings.append(c)
            c = []
            i = 0
        for person2 in persons_list:
            if person2.name == person1 and person2.thing == thing:
                a = lineyes[:indexyes] + person1 + lineyes[indexyes:]
                break
            else:
                b = lineno[:indexno] + person1 + lineno[indexno:]
        i = i + 1
        if a == "":
            c.append(b)
        else:
            c.append(a)
            a = ""

context_dict["listOfListsOfRelationsToThings"] = listOfRelationsToThings

在模板中,我然后遍历此列表,尝试仅打印people_list_nodups每行的名称数量:

            <tr>
                <th>Things/Persons</th>
              {% for person in persons_nodups %}
                <th>{{ person }}</th>
              {% endfor %}
            </tr>
              {% for thing in things %}
                <tr>
                <th>{{ thing }}</th>
                    {% for i in listOfListsOfRelationsToThings %}
                        {% for relation in i %}
                            {{ context_var|safe }}
                            {% autoescape off %}
                                <td>{{ relation }}<td>
                            {% endautoescape %}
                        {% endfor %}
                        </tr>
                    {% endfor %}
              {% endfor %}

但最后,模式看起来像这样,这意味着它只打印第一行,但是两次,由于某种原因打印出空格:

Thing/Person | PersonA                | PersonB           |
ThingA       | [green]PersonA[/green] |                   | [red]PersonB[/red]
ThingB       | [green]PersonA[/green] |                   | [red]PersonB[/red]

数据库中的值是正确的,所以我做错了什么?

0 个答案:

没有答案