我有一个模特名称Student:
class Student(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
unique_id = models.CharField(max_length=15)
email = models.EmailField(blank=True)
grade = models.ForeignKey(Grade)
hr_teacher = models.ForeignKey(User, related_name='hr_students')
parent = models.ForeignKey(User, related_name='children')
def __unicode__(self):
return u'%s, %s (G-%s, %s)' % (self.last_name, self.first_name, self.grade.short_name, self.unique_id)
def hr_teacher_absent(self):
return self.hr_teacher.groups.filter(name='Absent Teachers').count() > 0
def hr_booking(self):
return self.booking_set.filter(teacher=self.hr_teacher,status__uses_space=True)
def has_booking(self):
return bool(self.hr_booking())
def hr_booking_for_event(self, ptc_event):
return self.hr_booking().filter(period__ptc_event=ptc_event)
def has_booking_for_event(self, ptc_event):
return bool(self.hr_booking_for_event(ptc_event))
def delete_all_bad_bookings(self):
bad_bookings = self.booking_set.exclude(teacher=self.hr_teacher).delete()
class Meta:
ordering = ['grade','last_name','first_name']
每个学生都有一个家庭教师,这是一个组名为“教师”的用户(这些是默认用户,在django的管理员中定义的组)。我正在尝试获得至少有1名学生的小组教师用户列表。这是我的代码:
teacher_list_db = get_object_or_404(Group, name="Teachers").user_set.annotate(num_students=Count('hr_students')).filter(num_students__gt=0).order_by("last_name","first_name")
并返回一个空数组。
我阅读了django文档并找到了这个方法:
get_list_or_404(klass, *args, **kwargs)
我试过并卡在这里:
teacher_list_db = get_list_or_404(User.objects.order_by('last_name', 'first_name'), groups__name='Teachers')
我不知道如何处理注释部分,该部分计算了同一位老师的学生数量!
答案 0 :(得分:1)
好的,我刚想通了:
teachers_list_db = get_list_or_404(User.objects.order_by('last_name', 'first_name'), groups__name='Teachers')
if teachers_list_db:
teachers_list = []
for teacher in teacher_list_db:
if teacher.hr_students.all().count() >= 0:
teachers_list.append(teacher)
teachers_list 是我需要的列表。
耶! Django真棒! \米/