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?

Question:

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:

Utilizing

person.position_set.count()

is possible if you possess a

Person

occurrence labeled as

person

.


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

.count()

method on querysets. It’s important to avoid using

len()

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

len()

method will assess the queryset. Additional details can be found 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()


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