我想知道如何计算与某个ClassRoom相关的学生人数,并将当前数量放在一个字段中,这样每当我将学生添加到ClassRoom时,我都可以知道当前的学生人数在它。
class Student(models.Model):
ClassRoom = models.ForeignKey(ClassRoom)
class ClassRoom(models.Mode):
qtt_current_students =
------------编辑------------------
我尝试了以下内容,但qtt_current_students没有得到 instance.ClassRoom.student_set.count()
每当我添加学生时,该字段都没有
@receiver(pre_save, sender=Student)
def Student_pre_save(sender, instance, **kwargs):
instance.ClassRoom.qtt_current_students = instance.ClassRoom.student_set.count()
答案 0 :(得分:1)
@receiver(post_save, sender=Student)
def Student_pre_save(sender, instance, **kwargs):
ClassRoom.qtt_current_students = instance.ClassRoom.student_set.count()
试试这个,
答案 1 :(得分:0)
我试过这个,效果很好。
@receiver(post_save, sender=Student)
def student_post_save(sender, instance, **kwargs):
t = ClassRoom.objects.get(pk=instance.ClassRoom.pk)
t.qtt_current_students = instance.ClassRoom.student_set.count()
t.save()
@receiver(post_delete, sender=Student)
def student_post_delete(sender, instance, **kwargs):
t = ClassRoom.objects.get(pk=instance.ClassRoom.pk)
t.qtt_current_students = instance.ClassRoom.student_set.count()
t.save()