Search code examples
djangomany-to-manymanytomanyfield

Django Count how many manytomany relation ships in an attribute


This is my model:

class Set(models.Model):
    name = CharField(max_length = 25)
    teacher = ForeignKey(get_user_model(), null = False, on_delete = models.CASCADE)
    students = ManyToManyField(get_user_model(), related_name= 'set_students')

and I want to know how many students are in the manytomanyfield.

Ive tried this

set_ = Set.objects.get(pk=id_)
students = len(set_.students)

But that hasn't worked.

Thanks for any help!


Solution

  • You can use queryset's method count() directly on students field: set_.students.count().