我自己尝试过研究这个问题,但无法弄清楚,所以我希望有人能够为我提供一些指导。
我有以下2款:
class Group(models.Model):
short_name = models.CharField(max_length=10, primary_key=True) # company acronym
full_name = models.CharField(max_length=200)
learner_count = models.PositiveIntegerField(default=0)
contract = models.ForeignKey(Contract, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
startDate = models.DateField()
endDate = models.DateField()
notes = models.TextField(blank=True, null=True)
class Learner(models.Model):
...
group = models.ForeignKey(Group, on_delete=models.CASCADE)
当学习者被添加到组中或从组中删除时,是否可以动态更新组的 learner_count 字段?
我建议根本不要存储
Learner
计数。你不需要存储这个。该模型看起来像:
class Group(models.Model):
short_name = models.CharField(
max_length=10, primary_key=True
) # company acronym
full_name = models.CharField(max_length=200)
# learner_count = models.PositiveIntegerField(default=0)
contract = models.ForeignKey(Contract, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
startDate = models.DateField()
endDate = models.DateField()
notes = models.TextField(blank=True, null=True)
必要时您可以通过以下方式确定:
from django.db.models import Count
Group.objects.annotate(learner_count=Count('learner'))
由此
Group
产生的 Queryset
对象将具有额外的属性 .learner_count
以及相关 Learner
记录的数量。