我可以在django-tables2中制作一个二维表吗?

时间:2018-05-18 23:28:27

标签: python django html-table django-templates django-tables2

编辑: 大家好,我一直在寻找解决问题的方法,有些日子没有答案 我正在尝试使用从同一模型获得的数据制作二维表。 我们的想法是按行列出学生,列中的数据和各自单元格中的状态,这是一个二维表。

class DailyAttendanceStudent(models.Model):
    ATTENDANCE_CHOICES = (
        (None,''),
        (True,'Presente'),
        (False, 'Ausente')
        )
    date = models.DateField(default=datetime.datetime.now)
    status = models.NullBooleanField(choices=ATTENDANCE_CHOICES)
    student = models.ForeignKey('perfiles.Student')

这些是我的表:

class StudentAttendanceTable(tables.Table):
    nombres = tables.Column('nombres', accessor='Student.first_name')
    apellidos = tables.Column('apellidos', accessor='Student.last_name')
    date = tables.Column('fecha', accessor='date')#LinkColumn
    status = tables.Column('status', accessor='status')
    class Meta:
        model = DailyAttendanceStudent
        fields = ('nombres', 'apellidos', 'date', 'status')

以图形方式这就是我想要做的事情:

I want to do this

1 个答案:

答案 0 :(得分:2)

我想我会做这样的事情:

  • 按需要过滤DailyAttendanceStudent查询集,并将其传递给您的表格。
  • 为您的表实现自定义构造函数,执行以下操作:
    • 遍历查询集,将其转换为OrderedDict,并将用户ID作为密钥。对于任何新日期,您应该向实例添加新列,并将该日期的密钥添加到OrderedDict。
    • 新列可以是table.Column,也可以是专门用于满足您需求的内容。
    • 自定义构造函数应该调用父类的构造函数,将OrderedDict的项目作为数据传递,将日期列作为extra_columns传递。

在代码中,它可能如下所示:

from collections import OrderedDict
import django_tables2 as tables

class StudentAttendanceTable(tables.Table):
    nombres = tables.Column('nombres', accessor='student.first_name')
    apellidos = tables.Column('apellidos', accessor='student.last_name')

    def __init__(self, data, *args, **kwargs):
        rows = OrderedDict()
        extra_columns = {}
        for row in data:
            if row.student.id not in rows:
                rows[row.student.id] = {'student': row.student}
            rows[row.student.id][row.date] = row.status
            extra_columns[row.date.isoformat()] = tables.Column()  # use more specialized column if you get this to work
        super(StudentAttendanceTable, self).__init__(data=rows.values(), extra_columns=extra_columns.items(), *args, **kwargs)

您可能希望对传递给extra_columns的值进行排序,因为从数据库中检索的顺序可能不是所需的演示顺序。

相关问题