DjangoTables2从另一个模型添加列

时间:2018-03-17 14:51:10

标签: python django django-tables2

我有这个型号的DjangoTable:

var accs = await $.get(GetUrl("/accounts"));

表:

class Mark(models.Model)
    id_mark = models.AutoField(primary_key=True, verbose_name='Id запису')
    id_student = models.ForeignKey(Student, blank=False, null=False, default=None, on_delete=models.CASCADE,verbose_name='Студент')
    id_subject = models.ForeignKey(Subject, blank=False, null=False, default=None, on_delete=models.CASCADE,verbose_name='Предмет')
    mark = models.DecimalField(decimal_places=3, max_digits=5, blank=False, null=False, default=None, verbose_name='Оцінка')

    class Meta:
        verbose_name = 'Оцінка'
        verbose_name_plural = 'Оцінки'

    def __str__(self):
       return "{} {} {}".format(self.id_student, self.id_subject, self.mark)

我想使用此模型中的值添加列:

class Mark_Table(tables.Table):
    class Meta:
         model = Mark
         exclude = ('id_mark',)
         attrs = {'class': 'paleblue'}

现在我有字段学生主题标记,我想从另一个模型添加字段id_teacher,并且必须保持关系。

1 个答案:

答案 0 :(得分:0)

您可以使用table.Coulmn()在表格中添加外键值并指定accessor 如下所示:

id_teacher = tables.Column(accessor='id_subject.id_teacher')

所以你的Mark_Table会是这样的:

class Mark_Table(tables.Table):
    # Define all the custom fields here including any override or adding other fields and include it in fields in meta class
    id_teacher = tables.Column(accessor='id_subject.id_teacher')

    class Meta:
         model = Mark
         fields = ['mark', 'id_teacher']  # specify all the fields you want to display here
         attrs = {'class': 'paleblue'}

详细了解如何在docs

添加自定义字段