我的问题需要一些帮助。我已经创建了所有投资的清单,但现在我需要通过金融机构将它们分开。我正在尝试打印一份报告,该报告将在每个单独的页面上为每个金融机构进行所有投资,但我无法将它们分开。
例如我想要的是:
道明银行 - 来自我的查询的所有TD投资
Scotia Bank - 根据我的查询对Scotia的所有投资
等
以下是我的views.py,它包含查询并将所有信息添加到我的列表中。
任何人都可以帮我找到一种方法将其分开,以便我可以将它们与金融机构分开吗?
def confirmations_report(request, *args, **kwargs):
from investments.models import Investment, InvestmentManager
from reports.forms import ConfirmationsForm
import ho.pisa as pisa
import cStringIO as StringIO
import os.path
confirm_letter_list = []
context = {}
if request.POST:
form = ConfirmationsForm(request.POST)
if form.is_valid():
start_date = form.cleaned_data['start_date']
end_date = form.cleaned_data['end_date']
investments = Investment.objects.all().filter(contract_no = "",maturity_date__range=(start_date, end_date)).order_by('financial_institution')
for i in investments:
confirm_letter_list.append({
'fi':i.financial_institution,
'fi_address1': i.financial_institution.address1,
'fi_address2': i.financial_institution.address2,
'fi_city': i.financial_institution.city,
'fi_prov': i.financial_institution.state_prov,
'fi_country': i.financial_institution.country,
'fi_postal': i.financial_institution.postal,
'primary_owner': i.plan.get_primary_owner().member,
'sin': i.plan.get_primary_owner().member.client.sin,
'type': i.product.code,
'purchase_amount': i.amount,
'purchase_date': i.start_date,
})
context['confirmlist'] = confirm_letter_list
context['inv'] = investments
if request.POST.has_key('print_report_submit'):
context['show_report'] = True
context['mb_logo'] = os.path.join(os.path.dirname(__file__), "../../../media/images/mb_logo.jpg")
html = render_to_string('reports/admin/confirm_report_print.html', RequestContext(request,context))
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
response = HttpResponse(result.getvalue(), mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=unreceived-confirmations.pdf'
return response
else:
form = ConfirmationsForm()
context['form'] = form
return render_to_response('reports/admin/confirm_report.html', RequestContext(request, context))
答案 0 :(得分:2)
将defaultdict
与列表一起使用。
from collections import defaultdict
my_list = defaultdict(list)
for i in investments:
my_list[i.financial_institution].append({ ... })
以下是您将如何使用它:
{% for i in my_list.iteritems %}
Institution : {{ i.0 }}
{% for z in i|slice:"1:" %}
Total Items for {{ i.0 }} : {{ z|length }}
{% for d in z }}
{{ d.fi_address1 }}
....
{% endfor %}
{% endfor %}
{% endfor %}
这是一个简化的例子:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d['hello'].append({1:'One', 2:'Two'})
>>> for i in d.iteritems():
... print i[0]
... for z in i[1:]:
... print z
...
hello
[{1: 'One', 2: 'Two'}]
正如您所看到的,内部循环包含您添加的dicts列表,因此您需要相应地调整循环逻辑。