Python新手在这里...我的Django模型中有一堆RoomBooking
事件,其中包含启动和停止时间,我需要检索一个月内每个事件的总持续时间,按公司分组。目前看起来如下:
models.py:
class RoomBooking(models.Model):
room = models.ForeignKey(Room)
bookedBy = models.ForeignKey(User)
startTime = models.DateTimeField()
stopTime = models.DateTimeField()
views.py:
@login_required
def report_company(request, year, month):
if request.user.is_staff:
rooms_by_company = RoomBooking.objects.filter(startTime__year=year, startTime__month=month).order_by('bookedBy__userprofile__account')
result = [list(v) for l, v in groupby(sorted(rooms_by_company, key=lambda x: x.bookedBy.userprofile.account.name), lambda x: x.bookedBy.userprofile.account.name)]
if int(month) == 1:
prev_year = int(year) - 1
prev_month = 12
next_year = int(year)
next_month = int(month) + 1
else:
if int(month) == 12:
prev_year = int(year)
prev_month = int(month) - 1
next_year = int(year) + 1
next_month = 1
else:
prev_year = int(year)
prev_month = int(month) - 1
next_year = int(year)
next_month = int(month) + 1
return render_to_response(
'roombooking_report.html',
{
'booking_list': result,
'month_name': calendar.month_name[int(month)],
'month': month,
'year': year,
'prev_month': prev_month,
'prev_month_name': calendar.month_name[prev_month],
'prev_year': prev_year,
'next_month': next_month,
'next_month_name': calendar.month_name[next_month],
'next_year': next_year,
},
context_instance=RequestContext(request)
)
else:
t = get_template('403.html')
context = RequestContext(request)
return HttpResponse(t.render(context), status=403)
room_booking.html:
{% extends "base.html" %}
{% load url from future %}
{% block content %}
<div>
<h1>Room Booking Report for {{ month_name }} {{ year }}</h1>
<a href="{% url 'meetingroombooking.views.report_company' year=prev_year month=prev_month %}">< {{ prev_month_name }} {{ prev_year }}</a> |
<a href="{% url 'meetingroombooking.views.report_company' year=next_year month=next_month %}">{{ next_month_name }} {{ next_year }} ></a>
<div>
{% for company in booking_list %}
<h2>{{ company.0.bookedBy.userprofile.account.name }}</h2>
<ul>
{% for b in company %}
<li>{{ b.bookedBy.first_name }} {{ b.bookedBy.last_name }} booked {{ b.room }} for {{ b.startTime }} to {{ b.stopTime }} ({{ b.startTime|timesince:b.stopTime }})</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
</div>
</div>
{% endblock %}
我想在模板中添加<h2>
标签,表示该公司当月所有客房预订的总持续时间,但作为蟒蛇新手,我不知道从哪里开始!我已尝试更改在视图中分配给result
的列表,但我无法将其编译。
如何查询数据库中的这些值,将其添加到result
并将其显示在模板中?