doc:appunti:prog:django
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
doc:appunti:prog:django [2011/06/26 11:34] – [Mettere i dati nella vista] niccolo | doc:appunti:prog:django [2011/06/28 09:15] (current) – [Mettere i dati nella vista] niccolo | ||
---|---|---|---|
Line 223: | Line 223: | ||
output = template.render(variables) | output = template.render(variables) | ||
return HttpResponse(output) | return HttpResponse(output) | ||
+ | </ | ||
+ | |||
+ | ==== Visualizzazione e aggregazione dei dati ==== | ||
+ | |||
+ | Nel codice della **view** è possibile accedere ai dati (i **model**) sfruttando anche le relazioni tra essi (le //foreign key// delle tabelle del database). È possibile anche usare funzioni di aggregazione. | ||
+ | |||
+ | Ecco un esempio di una vista dell' | ||
+ | |||
+ | <code python> | ||
+ | from django.http import HttpResponse | ||
+ | from django.template import Context | ||
+ | from django.template.loader import get_template | ||
+ | |||
+ | from django.db.models import Sum, Count | ||
+ | |||
+ | from django.contrib.auth.models import User | ||
+ | #from spese.models import Expense | ||
+ | |||
+ | def balance(request): | ||
+ | |||
+ | users = User.objects.all() | ||
+ | |||
+ | max_expense = 0 | ||
+ | for user in users: | ||
+ | user.aggr = user.expense_set.aggregate(Count(' | ||
+ | if user.aggr[' | ||
+ | max_expense = user.aggr[' | ||
+ | for user in users: | ||
+ | user.balance = user.aggr[' | ||
+ | |||
+ | template = get_template(' | ||
+ | variables = Context({ | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | }) | ||
+ | output = template.render(variables) | ||
+ | return HttpResponse(output) | ||
+ | </ | ||
+ | |||
+ | Ecco infine il template **'' | ||
+ | |||
+ | <code html> | ||
+ | < | ||
+ | < | ||
+ | < | ||
+ | {% if users %} | ||
+ | <table border=" | ||
+ | <tr> | ||
+ | < | ||
+ | < | ||
+ | < | ||
+ | < | ||
+ | </tr> | ||
+ | {% for user in users %} | ||
+ | <tr> | ||
+ | < | ||
+ | < | ||
+ | < | ||
+ | < | ||
+ | {% endfor %} | ||
+ | </ | ||
+ | {% else %} | ||
+ | <p>No users found.</ | ||
+ | {% endif %} | ||
+ | </ | ||
+ | </ | ||
</ | </ | ||
===== Webserver di test ===== | ===== Webserver di test ===== |
doc/appunti/prog/django.1309080848.txt.gz · Last modified: 2011/06/26 11:34 by niccolo