在一个数据库中使用四个模型,我想计算一个课程的员工总数。
此工作代码目前计算:
models.py
class Course(models.Model):
name = models.CharField(max_length=75)
class Employee(models.Model):
first_name = models.CharField(max_length=75)
surname = models.CharField(max_length=75)
class CourseDetail(models.Model):
course = models.ForeignKey(Course)
date = models.DateField(blank=True, null=True)
renew_date = models.DateField(blank=True, null=True, default=None)
attendance = models.ManyToManyField(Employee, through='CourseDetailAttendance')
class CourseDetailAttendance(models.Model):
course_details = models.ForeignKey(CourseDetail)
employee = models.ForeignKey(Employee)
我想返回每个独特课程组的候选人总数,即Course01 = 24名候选人
到目前为止我所拥有的......
views.py
from django.db.models import Count
def BetweenDates(request):
start_date = '2013-03-01'
end_date = '2013-03-30'
cr = CourseDetail.objects.filter(date__range=(start_date, end_date))
cc_count = cr.count()
cc_grouped = cr.values('course__name').annotate(Count('course'))
cc_grouped_count = cc_grouped.count()
cc_attendance = ???????????
context = {"cc_grouped_count": cc_grouped_count,
"courses_grouped": cc_grouped,
"date_range": cr,
"courses_count":cc_count,
"cc_attendance": cc_attendance,
}
return render_to_response('between_dates.html', context, context_instance=RequestContext(request))
between_dates.html
{% extends 'base.html'%}
{% block content %}
<h4><p>{{ cc_grouped_count }} courses delivering {{ courses_count }} course instances between {{ startdate }} and {{ enddate }}</p></h4>
{% for cs in courses_grouped %}
<div class = "news-articles ingrid in-thirds">
<div class = "unit">
<div class= "box">
{{ cs.course__name }}
</div>
</div>
<div class = "unit">
<div class= "box">
{{ cs.course__count }}
</div>
</div>
<div class = "unit">
<div class= "box">
total number of candidates goes here {{ cc_attendance }}
</div>
</div>
</div>
{% endfor %}
答案 0 :(得分:0)
假设,按课程分组,您指的是某一天的课程(CourseDetails -instance),并且您希望按课程名称和日期查询:
course_details = CourseDetail.objects.get(course__name='Django 101', date='2013-03-01')
cc_attendance = CourseDetailAttendance.objects.filter(course_details=course_details).count()
如果您想要某个课程的参加者,无论他们何时参加,请运行
course_details = CourseDetail.objects.filter(course__name='Django 101')
cc_attendance = CourseDetailAttendance.objects.filter(course_details__in=course_details).count()
在特定时间范围内获取参与者人数:
course_details = CourseDetail.objects.filter(course__name='Django 101', date__range=[start_date, end_date])
cc_attendance = CourseDetailAttendance.objects.filter(course_details__in=course_details).count()
顺便说一下,是否有可能在同一天拥有给定课程的几个实例(例如Django 101)?如果没有,我建议你把这个组合做成独特的:
class CourseDetail(models.Model):
course = models.ForeignKey(Course)
date = models.DateField(blank=True, null=True)
renew_date = models.DateField(blank=True, null=True, default=None)
attendance = models.ManyToManyField(Employee, through='CourseDetailAttendance')
class Meta:
unique_together = ('course', 'date')