2012-11-09 94 views
1

這似乎與this question非常相似。當點擊鏈接按pass_count排序時,我得到:非查詢集數據排序

無法將關鍵字u'pass_count'解析爲字段。選項包括:建立,build_no

models.py:

class Run(DashboardBaseModel): 
class Meta: 
    db_table = 'runs' 

build_no = models.CharField(max_length=200, db_index = True) 
release = models.CharField(max_length=200, db_index = True) 
extra_fields = [ 
     'pass_count', 
     ] 

@property 
def pass_count(self): 
    passes = 0 
    for build in self.build_set.all(): 
     passes += build.pass_count 
    return passes 

tables.py:

class CombineTable(tables.Table): 
build_no = tables.LinkColumn('run', args=[A('release'), A('id')], verbose_name="Build") 
pass_count = tables.Column(verbose_name="Passed", attrs={"td": {"class": "num"}, "th": {"class": "num"}}) 

是否有辦法來解決此問題?

回答

0

您需要將數據轉換爲字典以允許非數據庫字段可排序。

runs = Run.objects.all() 

table_data = [] 
for run in runs: 
    passes = 0 
    for build in run.build_set.all(): 
     passes += build.pass_count 
    table_data.append(dict(
     build_no=run.build_no, 
     release=run.release, 
     pass_Count=passes, 
    )) 

table = CombineTable(table_data) 

注意:這將爲每次運行查詢數據庫一次。對此的解決方案需要構建QuerySet,並在所有構建上循環,將每個構建的pass_count添加到基於運行的字典中。