2011-09-14 64 views
2

我使用django-tables(http://pypi.python.org/pypi/django-tables/0.2)來呈現MySQL表的內容。Django:django_tables排序方法

表映射到的模型包含幾個函數,這些函數是轉換函數或行內容的聚合。

例如:

class Example(models.Model): 

    STATUS_1 = 0 
    STATUS_2 = 1 
    STATUS_3 = 2 

    STATUS_CHOICES = ( 
       (STATUS_1, _('Status One')), 
       (STATUS_2, _('Status Two')), 
       (STATUS_3, _('Status Three')), 
      ) 


    #This gives a nice drop down when rendered in a form... 
    status = models.IntegerField(choices=STATUS_CHOICES, 
          default=STATUS_1, 
          verbose_name=_('Status')) 

    #This is the function to produce the text for a choice... 
    def status_text(self): 
     return self.STATUS_CHOICES[self.status][1] 

    #A function that inspects items that link to 'Example' 
    #and creates an aggregate string value 
    def openissues(self): 
     answer = _("No") 
     linked_issues = self.issues.all() 
     for thisissue in linked_issues: 
      if (not thisissues.resolved): 
       answer = _("Yes") 
       break 

     return answer 

然後在我的表類的定義,我有:

import django_tables 
from django.utils.translation import ugettext_lazy as _ 

class ExampleTable(django_tables.ModelTable): 
    . 
    . 
    status_text = django_tables.Column(verbose_name=_('Status')) 
    openissues = django_tables.Column(verbose_name=_('Open Issues')) 
    . 
    . 

我的觀點是建立這樣的:

def decision_list(request): 
    . 
    . 
    objects = Example.objects.all() 
    table = ExampleTable(objects, order_by=request.GET.get('sort')) 
    return render_to_response('example_list.html', 
     RequestContext(request, dict(example=example))) 

最後的模板樣子這個:

<table id="example-list" cellspacing="0"> 
<tr> 
    {% for column in example.columns %} 
<th id="{{ example.name }}"{% if example.is_ordered_straight %} class="sorted straight"{% endif %}{% if column.is_ordered_reverse %} class="sorted reverse"{% endif %}><a href="?sort={{ column.name_toggled }}">{{ column }}</a></th> 
    {% endfor %} 
</tr> 
{% for thisexample in example.rows %} 
    <tr> 
     <td>{{ thisexample.id }}</td> 
     <td><a href="{% url a_url %}">{{thisexample.name}}</a></td> 
     <td>{{ thisexample.status_text }}</td> 
     <td>{{ thisexample.openissues }}</td> 

    </tr> 
{% endfor %} 
</table> 

(注:我編輯的代碼位,只包括相關零部件,並改了個名字,以更通用的東西,所以它可能是更容易理解)

無論如何,你可以看到希望我想能夠在用戶單擊列標題時對方法的status_text()和openissues()進行排序。

這不起作用。對於django_tables

文件說:「不是基於模型字段自定義列不支持排序,無論sortable特性(它被忽略)的。」

有沒有一種方法可以讓用戶對模型函數進行排序?這似乎是很多人想要做的事情。

回答

0

django的ORM層的一個重要特性是對DBSet進行排序和過濾QuerySet對象。 模型類中的方法或屬性在應用程序服務器上進行評估,並且不會映射到數據庫列。因此你不能對這些進行排序。