[Django]-Django Model count in Foreign key

5👍

Yes, if you have a Person instance with name person, you can use person.position_set.count().

1👍

No matter, if you are trying to get the count of all objects or from the set of foreign key as @MostafaR suggested. You should use the .count() method on querysets. Also make sure you do not use len() if all you are looking for is the count and not the objects as len() method will evaluate the queryset. More information here.

To get the count of all objects

models.Position.objects.all.count()

To get the count of objects using foreign key

person = models.Person.objects.get(pk=1, **kwargs)
person.position_set.count()
👤Amyth

0👍

You need to create a method in Person model

class Person(models.Model):
 # ...
     def position(self):
         return self.position_set.count()

Leave a comment