Python django-tables2从hstore向表类添加动态列

Python django-tables2从hstore向表类添加动态列,python,django,hstore,django-tables2,Python,Django,Hstore,Django Tables2,我的一般问题是:我是否可以使用(Django 1.8.9)中存储的数据为的现有表类动态生成列?例如,假设我有一个模型: from django.contrib.postgres import fields as pgfields GameSession(models.Model): user = models.ForeignKey('profile.GamerProfile') game = models.ForeignKey('games.Game') last_ac

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

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)
现在,假设我有一个表定义为:

GameSessionTable(tables.Table):
    class Meta(BaseMetaTable):
        model = GameSession
        fields = []
        orderable=False

    id = tables.LinkColumn(accessor='id', verbose_name='Id', viewname='reporting:session_stats', args=[A('id')], attrs={'a':{'target':'_blank'}})
    started = DateTimeColumn(accessor='startdata.when_started', verbose_name='Started')
    stopped = DateTimeColumn(accessor='stopdata.when_stopped', verbose_name='Stopped')
    game_name = tables.LinkColumn(accessor='game.name', verbose_name='Game name', viewname='reporting:game_stats', args=[A('mainjob.id')], attrs={'a':{'target':'_blank'}})
我希望能够为所有
GameSession
s的额外信息列中存储的每个键添加列。我试图覆盖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())
只是提一下,我已经看过了,但是没有太大的帮助,因为那里的用例与模型的字段相关,而我的情况略有不同,正如你在上面看到的


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

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

因此,myinit()函数现在看起来如下所示:

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.columns(它们是BoundColumn实例)替换为self.base\u columns。这允许超类在初始化<代码>表< /代码>类时,也考虑这些。

这可能不是最优雅的解决方案,但它似乎对我起到了作用