我的一般问题是:是否可以使用存储在HStoreField(Django 1.8.9)中的数据为django-tables2的现有Table类动态生成列?举例来说,假设我有一个模型:
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
的extra_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这样的完全不同的库?
最佳答案
设法在一定程度上弄清楚了这一点。我在上面运行的代码有些错误,因此我更新了它以在运行超类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.base_columns替换了self.columns.columns(这是BoundColumn实例)。这样,允许超类在初始化
Table
类时也考虑这些问题。可能不是最优雅的解决方案,但这似乎对我有用。