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

时间:2015-03-16 03:57:49

标签: python django django-admin

我正在编写一个动作来设置一个字段等于通过外键附加到它的实例数量(见下文)

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,它是否仅在模板中有效?什么是最好的方法来计算这个数字?

1 个答案:

答案 0 :(得分:0)

使用backward relation

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