Djangotables2从hs向table类添加动态列

2024-04-24 07:22:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我的一般问题是:我可以使用存储在HStoreField(Django 1.8.9)中的数据为django-tables2的现有类动态生成列吗?例如,假设我有一个模型:

from django.contrib.postgres import fields as pgfields

GameSession(models.Model):
    user = models.ForeignKey('profile.GamerProfile')
    game = models.ForeignKey('games.Game')
    last_achievement = models.ForeignKey('games.Achievement')
    extra_info = pgfields.HStoreField(null=True, blank=True)

现在,假设我有一个定义为:

^{pr2}$

我希望能够为存储在所有GameSessionextra_info列中的每个键添加列。我尝试覆盖GameSessionTable类的init()方法,在该方法中我可以访问queryset,然后生成一组GameSession对象的所有键,然后将它们添加到self,但是好像不管用。代码如下:

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

    if data:
        extra_cols=[]
        # just to be sure, check that the model has the extra_info HStore field
        if data.model._meta.get_field('extra_info'):
            extra_cols = list(set([item for q in data if q.extra_info for item in q.extra_info.keys()]))
        for col in extra_cols:
            self.columns.columns[col] = tables.Column(accessor='extra_info.%s' %col, verbose_name=col.replace("_", " ").title())

仅举一提,我已经看过https://spapas.github.io/2015/10/05/django-dynamic-tables-similar-models/#introduction,但没有多大帮助,因为那里的用例与模型的字段相关,而我的情况与您在上面看到的略有不同。在

只是想检查一下,这是可能的还是我必须为这个数据定义一个完全不同的表,或者可能使用一个完全不同的库,比如django-reports-builder?在


Tags: djangoinselfinfofordataifinit
1条回答
网友
1楼 · 发布于 2024-04-24 07:22:47

在一定程度上解决了这个问题。我上面运行的代码有点错误,所以我更新了它以在超类init()运行之前运行我的代码,并更改了添加列的位置。在

因此,我的init()函数现在如下所示:

def __init__(self, data, *args, **kwargs):
    if data:
        extra_cols=[]
        # just to be sure, check that the model has the extra_info HStore field
        if data.model._meta.get_field('extra_info'):
            extra_cols = list(set([item for q in data if q.extra_info for item in q.extra_info.keys()]))
        for col in extra_cols:
            self.base_columns[col] = tables.Column(accessor='extra_info.%s' %col, verbose_name=col.replace("_", " ").title())

    super(GameSessionTable, self).__init__(data, *args, **kwargs)

请注意,我替换了self.columns.列(它们是BoundColumn实例),使用self.base_列。这允许超类在初始化Table类时也考虑这些问题。在

可能不是最优雅的解决方案,但它似乎对我有好处。在

相关问题 更多 >