[英]django-tables2 add dynamic columns to table class from hstore
我的一般問題是:我可以使用存儲在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 () 方法,在那里我可以訪問查詢集,然后創建一組我的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.columns.columns(這是綁定列實例)與self.base_columns。 這允許超類在初始化Table
類時也考慮這些。
可能不是最優雅的解決方案,但它似乎對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.