尝试在django_tables2中插入带有外部字段列表的新列

时间:2014-10-24 09:49:27

标签: python django django-tables2

我正在使用django_tables2来显示“修复细节”列表。到现在为止还挺好。但是我想添加一个新字段(它不在模型中):服务报告列表。关系是1对多。并显示另一个型号中的序列号。这是非常困难,因为我添加了字段但render_NEW_FIELD不起作用,我无法访问服务报告列表,因为在表模型中我只能访问记录而不是repair_detail模型。我正在使用django_tables 0.15

维修/ models.py

class RepairDetail(models.Model):
    repair = models.ForeignKey('Repair')
    repair_detail_number = models.IntegerField()
    article_code = models.CharField(max_length=30)
    registered_date = models.DateField(null=True)
    registered_uid = models.IntegerField(null=True)
    registered_initials = models.CharField(max_length=2, null=True)
    customer_reference = models.CharField(max_length=20, null=True)
    db2_recnum = models.IntegerField()

    def __unicode__(self):
        return str(self.repair_detail_number)


class ServiceReport(models.Model):
    repair_detail = models.ForeignKey('RepairDetail')
    status = models.ForeignKey('ServiceReportStatus', on_delete=models.PROTECT)
    serial_number = models.ForeignKey('core.SerialNumber')
    customer = models.ForeignKey('core.Company')
    contact = models.ForeignKey('core.Contact', null=True, on_delete=models.SET_NULL)
    project = models.ForeignKey('core.Project')
    project_code = models.CharField(max_length=4)
    identifier = models.CharField(max_length=1)
    repair_date = models.DateField(null=True)
    repair_uid = models.IntegerField(null=True)
    repair_initials = models.CharField(max_length=2, null=True)
    booking_date = models.DateField(null=True)

芯/ models.py

class SerialNumber(models.Model):
    product = models.ForeignKey("Product")
    panel = models.ForeignKey("Panel", null=True, blank=True, default = None)
    serial_number = models.CharField(max_length=30, default='')
    manifest = models.TextField(null=True)

    def __unicode__(self):
        return self.serial_number

维修/ tables.py

class RepairDetailTable(tables.Table):
    #serials = tables.Column(accessor='servicereport.serialnumber.serialnumber')
    serial = tables.Column()

    def __init__(self, *args, **kwargs):
        super(RepairDetailTable, self).__init__(*args, **kwargs)

    class Meta(object):
        model = RepairDetail
        fields = ('id', 'repair_detail_number', 'article_code', 'registered_date', 'registered_initials', 'customer_reference', 'serials')
        attrs = {'class': 'table table-striped table-bordered protonic'}
        empty_text = "No records found."

1 个答案:

答案 0 :(得分:1)

如果你想要(1:N而不是N:1)连接表格单元格中的所有相关模型,请尝试通过设置属性在模型层中执行此操作,如下所示:

class RepairDetail(models.Model):
    # ...

    @property
    def service_reports_list(self):
        return self.servicereport_set.all()

定义您自己的列(继承tables.Column)并覆盖render方法

将其添加到您的表类:

class RepairDetailTable(tables.Table):
    # ...
    service_reports_list = YourOwnColumn(some_kwargs)
    # ...