django-tables2 上混合多个外键的自定义列

Custom column on django-tables2 that mix multiple foreignkeys

我正在尝试在 django-tables2 上创建一个自定义列,其功能是 returns 来自 3 个可能的外键(只有一个可以不为空)的非空字段。这是我所做的:

Models.py

class Sitiocancelado(models.Model):
    x = models.OneToOneField(X, on_delete=models.CASCADE, null=True,blank=True)
    y = models.OneToOneField(Y, on_delete=models.CASCADE, null=True, blank=True)
    z = models.OneToOneField(Z, on_delete=models.CASCADE, null=True, blank=True)
    fecha_de_cancelacion = models.DateField(null=True, blank=True)
    comentarios = models.TextField(max_length=200, null=True, blank=True)
    slug = models.SlugField(max_length=100, editable=False)

    def __str__(self):
        return self.z.y.x.nombre_del_sitio

Tables.py

class SitiocanceladoTable(tables.Table):

    def columna_combinada(table):
        if x == None:
            if y == None:
                return z
            else:
                return y
        else:
            return x

    Sitio = tables.Column(columna_combinada)

    class Meta:
        model = Sitiocancelado
        attrs = {
            'class': 'table table-striped table-bordered', 
            'id': 'example', 
            'width' : '100%', 
        }
        fields = ('Sitio',)
        exclude = ('id', 'slug', 'sitioproyecto', 'sitiocontratado', 'sitiooperando',)

有意义吗?

自定义列并不是这样工作的。您基本上有两个选择:

render_<columnname>

这看起来有点像你的例子。在 table class 上定义名称为 render_<column name> 的列和方法。无需将该名称提供给您定义的列。您的示例如下所示:

class SitiocanceladoTable(tables.Table):
    Sitio = tables.Column(empty_values=())

    class Meta:
        model = Sitiocancelado

    def render_Sitio(self, record):
        if record.x == None:
            if record.y == None:
                return record.z
            else:
                return record.y
        else:
            return record.x

此方法适用于 one-offs。它没有太多多余的代码,并且代码与table.

的其余定义非常接近

请注意,我添加了 emtpy_values=()。这将确保您使用的渲染函数的自定义实现,即使 django-tables2 认为您的列是空的。自定义列有责任呈现正确的默认值。

Subclassing Column

如果您需要在多个 table 中或在同一 table 中多次使用此列的功能,subclass Column 可能更简洁或多个 specific Column 实现之一。

您的示例可能如下所示:

class CombinedFKColumn(tables.Column):
    def render(self, record):
        return getattr(record, 'x', getattr(record, 'y', getattr(record, 'z', self.default)))

class SitiocanceladoTable(tables.Table):
    Sitio = tables.CombinedFKColumn(empty_values=())

    class Meta:
        model = Sitiocancelado