Goun2 Goun2 -4 years ago 64
Python Question

How to count and return the objects related to a table to a model field

I'd like to know how to count the number of Students related to a certain ClassRoom, and to place the current quantity to a field so whenever I add a student to a ClassRoom I can know the current number of students in it.

class Student(models.Model):
ClassRoom = models.ForeignKey(ClassRoom)


class ClassRoom(models.Mode):
qtt_current_students =


------------Edit ------------------

I tried the following, but the qtt_current_students doesn't get the
instance.ClassRoom.student_set.count()

Whenever I add an Student the field doesn't udate

@receiver(pre_save, sender=Student)
def Student_pre_save(sender, instance, **kwargs):
instance.ClassRoom.qtt_current_students = instance.ClassRoom.student_set.count()

Answer Source

I tried this, and it worked great.

@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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download