python - Field added to django querysets not working in django-tables2 -
i have set of imported bank account entries oredered date , sequence number within each date.
i'm using django-tables2 display data, i'm adding running total column calculate before rendering view.
to i'm trying add field query set following code:
import django_tables2 tables django_tables2 import requestconfig .models import bank, bankimportfile, importfileentry ... other imports class banklistingtable(tables.table): memo = tables.column(verbose_name = 'description') total = tables.column(verbose_name = 'running total') class meta: model = importfileentry attrs = {'class': 'paleblue'} def bank_listing(request, bankname): bank = get_object_or_404(bank, pk=bankname) qs = importfileentry.objects.filter(account=bank(bank)).order_by('date', 'seq') total = 0 row in qs: total += row.amount row.total = total table = banklistingtable(qs) requestconfig(request).configure(table) return render(request, 'banking/bank_transactions.html', {'table': table, 'bank': bank})
if step through code in pdb
can examine both row.total
, qs[<row number>].total
, appear have correct data.
yet in rendered table in total column --
if convert queryset
list , leave else unchanged works:
def bank_listing(request, bankname): bank = get_object_or_404(bank, pk=bankname) qs = importfileentry.objects.filter(account=bank(bank)).order_by('date', 'seq') qs = list(qs) # added line , works total = 0 row in qs: total += row.amount row.total = total table = banklistingtable(qs) requestconfig(request).configure(table) return render(request, 'banking/bank_transactions.html', {'table': table, 'bank': bank})
my queryset
large 9-year history of business bank account seems inefficient copy list
.
i've seen other examples on stackoverflow
seem imply original code should work , pdb testing implies should. in django-tables2
?
as said in comment, did working in case. however, wouldn't recommend evaluating query for
loop since load queryset memory (it has same effect using list
). instead, i'd recommend adding row query contain running sum.
to do should use extra
queryset method add field queryset. find out how running total sql can check answer question: how running sum of column in sql server
also, since mention queryset large should add pagination table -- , not benefit pagination if evaluate queryset for-loop
. feel free ask again if have trouble implementing extra()
method.
update: answer op's comment (i not sure names of tables & fields i'll make guess:
select amount, ( select sum(amount) importfileentry ife1 ife1.date < ife.date ) + ( select sum(amount) importfileentry ife2 ife2.date = ife.date , ife2.seq < ife.seq ) running_total importfileentry ife order ife.date, ife.seq
one (complex) query -- as running_total
extra()
queryset method create :)
Comments
Post a Comment