2012-06-14 9 views
9

La documentazione dire:non queryset ordinamento dei dati in django-tables2

Where the table is backed by a model, the database will handle the ordering. Where this is not the case, the Python cmp function is used and the following mechanism is used as a fallback when comparing across different types: ...

Ma questo è possibile in una tabella che è sostenuta da un modello, su una colonna personalizzata? per esempio.

class MyModel(models.Model): 
    x = models.IntegerField() 
    y = models.IntegerField() 

    def z(self): 
     return x+y 

class MyTable(tables.Table): 
    z = tables.Column() 
    class Meta: 
     model = MyModel 

Quando provo qualcosa di simile, la colonna visualizza OK, ma quando clicco sul colonna per ordinare, ottengo questo errore:

Caught FieldError while rendering: Cannot resolve keyword u'z' into field. Choices are: ...

A quanto pare questo è dovuto al fatto z non si trova nella tabella del database.

C'è un modo per aggirare questo?

+2

Questo è un bug/mancanza di funzionalità in django-tables2. Ti dispiacerebbe aggiungere un problema a http://github.com/bradleyayers/django-tables2/issues per favore? L'ho colpito recentemente, ma ho dimenticato di seguirlo. –

+0

Si noti che [è stato aperto un problema] (https://github.com/bradleyayers/django-tables2/issues/82) ma questo particolare problema non è stato risolto. –

risposta

2

Non è possibile utilizzare un set di query se si ordina su un attributo che non ha una colonna di database. Puoi passare una lista al tuo tavolo però.

Assumendo che il models.py assomiglia a questo:

from django.db import models 

class MyModel(models.Model): 
    def foo(self): 
     return something_complex() 

si potrebbe avere tables.py che assomiglia a questo:

import django_tables2 as tables 
from .models import MyModel 

class MyModelTable(tables.Table): 
    foo = tables.Column() 

    class Meta: 
     model = MyModel 

Poi, nel tuo views.py:

from django_tables2.config import RequestConfig 
from django.core.paginator import InvalidPage 
from django.shortcuts import render 

def view_my_models(request): 
    # use a list so django_tables2 sorts in memory 
    my_models = list(MyModel.objects.all()) 

    my_models_table = MyModelTable(my_models) 
    RequestConfig(request).configure(my_models_table) 

    try: 
     page_number = int(request.GET.get('page')) 
    except (ValueError, TypeError): 
     page_number = 1 

    try: 
     my_models_table.paginate(page=page_number, per_page=10) 
    except InvalidPage: 
     my_models_table.paginate(page=1, per_page=10) 

    template_vars = {'table': my_models_table} 
    return render(response, "view_my_models.html", template_vars) 

C'è anche an open ticket discussing this issue.

+0

convertire il queryset in una lista ha funzionato per me, grazie per quel suggerimento! – Matt