如何计算每个查询集的实例数?姜戈

How can I count the number of instances per a queryset? Django

我正在编写一项操作,将一个字段设置为等于通过外键附加到它的实例数(见下文)

Models.py

 class competition(models):
    competition_name = models.CharField(max_length = 50)

 class people(models):
    competition = models.ForeignKey(competition)
    fullname = models.CharField(max_length = 100)

Admin.py

def people_in_competition:
     for X in queryset:
         X.number_of_people = X.count(X.set_all) #(I want the number of people in this competition in this part)
         X.save()

当然这给了我一个错误,因为我似乎无法在 admin.py 中使用 _set_all,它只适用于模板吗?计算该数字的最佳方法是什么?

使用backward relation:

X.number_of_people = X.people_set.all().count()