Django 泛型 ListView,引用 object_list 中的每一项

Django generic ListView, refering to each items in the object_list

我想知道添加上下文的ListView中每次训练的受训人数。

我搜索了如何引用 ListView 中的每个项目,以便对每个项目执行进一步查询。

如果有人知道更有效的方法,我将不胜感激

class TrainingsView(ListView):
    model = NewHireTraining
    template_name = 'nht/trainings.html'
    context_object_name = 'trainings'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['headcount'] = Trainee.objects.filter(new_hire_training = self.SOMETHING).count()
        return context

添加 NewHireTraining 和 Trainee 模型:

class NewHireTraining(models.Model):
    location = models.ForeignKey(Location, on_delete=models.CASCADE)
    program = models.ForeignKey(Program, on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    trainer = models.ForeignKey(Trainer, on_delete=models.RESTRICT)
    start_date = models.DateField()
    nesting_date = models.DateField()
    production_date = models.DateField()

    def __str__(self):
        return str(self.program) + ' ' + str(self.project) + ' ' + str(self.start_date)


class Trainee(models.Model):
    first_name = models.CharField(max_length=55)
    last_name = models.CharField(max_length=55)
    employee_number = models.IntegerField()
    hire_date = models.DateField()
    is_term = models.BooleanField(default=False)
    new_hire_training = models.ForeignKey(NewHireTraining, on_delete=models.CASCADE, default="")

    def __str__(self):
        return self.first_name + ' ' + self.last_name

您可以用 Trainee 的数量注释查询集:

from django.db.models import <strong>Count</strong>

class TrainingsView(ListView):
    model = NewHireTraining
    template_name = 'nht/trainings.html'
    context_object_name = 'trainings'
    queryset = NewHireTraining.objects.annotate(<strong>headcount=Count('trainee')</strong>)

从这个查询集中产生的 NewHireTraining 个对象将有一个额外的属性 .headcount 以及相关的 Trainee 的总数。

在模板中,您可以使用以下方式呈现:

{% for training in trainings %}
    {{ trailing }}: {{ trailing<strong>.headcount</strong> }}
{% endfor %}