在单个HTML表中显示链接的数据库结果

时间:2016-06-27 18:24:56

标签: python django django-templates html-table

我有几个由外键链接的数据库表(你必须在这里原谅基本的例子,我现在无法复制/粘贴我的开发环境)。

# models.py
class Task(models.Model):
    details = models.ForeignKey(Details)
    task = models.CharField(max_length=1024, null=false)

class Activity(models.Model):
    task = models.ForeignKey(Task)
    activity = models.CharField(max_length=1024)

class Resources(models.Model):
    activity = models.ForeignKey(Activity, null=false)
    resources = models.CharField (max_length=1024)

我需要在单个表格中显示这些结果。请注意,任务可以没有活动,活动可能没有任何资源等。例如:

  • 任务1
    • 活性1
      • 资源1
      • 资源2
    • 活性2
  • 任务2
    • ...等...

到目前为止,我已经在forms.py中创建了一个表,其中包含可能存在于数据库结果中的所有字段。所以:

# forms.py
class ViewTable(tables.Table):
    task = tables.Column(default=' ')
    activity = tables.Column(default=' ')
    resource = tables.Column(default=' ')

然后我使用itertools.chain以正确的顺序将结果链接在一起,然后将它们渲染到模板中。我在这里死路一条:

# views.py
table = None
for task in tasks:
    if table:
        table = list(chain(table, task)
    else:
        table = task

    for activity in Activities.objects.filter(tasks=task):
        table = list(chain(table, activity))
        for resource in Resources.objects.filter(activity=activity):
            table = list(chain(table, resource))

return render(request, 'table.html', {'table', table, })


# table.html
<table>
    <tr>
        <th>Tasks</th>
        <th>Activity</th>
        <th>Resources</th>
    </tr>
{% for item in table %}
    <tr>
        <th>{{ item.task }}</th>
        <th>{{ item.activity }}</th>
        <th>{{ item.resource }}</th>
    </tr>
{% endfor %}
</table>

这不起作用,因为如果我只有一个任务(没有任何活动或资源),那么该对象是不可迭代的,所以当我尝试在模板中渲染它时会出错。 / p>

但总的来说,我觉得这是一种草率而缓慢的做事方式,而我却无法想出更好的方法。欢迎修复或完全替代建议!

总体目标是获得如下所示的内容:

Tasks     Activities     Resources
-------------------------------------
task1
           activity1
                         resource1
                         resource2
           activity2
task2

1 个答案:

答案 0 :(得分:0)

I didn't realize that I could iterate through an object and add each of those items to a list. I was able to solve my own problem like so:

all = []

task = Tasks.objects.get(id=1)
all.append(task)

activities = Activities.objects.filter(task_id=task)
for activity in activities:
    all.append(activity)
    resources = Resources.objects.filter(activity_id=activity)
    for resource in resources:
        all.append(resource)

From there i'm able to just drop all into my template and access {{ all.activity_num }}, etc.

I guess I need to do some more reading about how objects are constructed. Thanks!