Counting Django Models within a Foreign Key Relationship

After retrieving an organization with the pk, attempting to delete it can be checked for its deletability. To detect what related model objects or rows would be deleted with the deletion of a particular model object or row, one might ask the question, “Is there a way to determine the number of positions in this type of Person model?


I have two models.

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
class Position(models.Model):
    person = models.ForeignKey(Person)
    description = models.CharField(max_length=50)

Could you assist me in determining the number of positions present in the Person model? I am looking for a way to count them within the model itself, similar to using Person.position.count. Any assistance is appreciated, thank you.

Solution 1:



is possible if you possess a


occurrence labeled as



Solution 2:

Whether you’re attempting to obtain the total number of objects or just from the
foreign key
set recommended by @MostafaR, it’s recommended to utilize the


method on querysets. It’s important to avoid using


if you’re only interested in the count and not the objects since the


method will assess the queryset. Additional details can be found here.

To get the count of all objects

To get the count of objects using foreign key
person = models.Person.objects.get(pk=1, **kwargs)

Solution 3:

A method should be made in the Person model.

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

Frequently Asked Questions