Nethan
Nethan

Reputation: 261

Django Model count in Foreign key

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)

Is there a way that i can count how many positions are there in this kind of Person model? Like Person.position.count..some sort of this. Please help me. This is counting inside model only. please.

Upvotes: 3

Views: 4270

Answers (3)

Emmanuel Osimosu
Emmanuel Osimosu

Reputation: 6004

You need to create a method in Person model

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

Upvotes: 0

Amyth
Amyth

Reputation: 32949

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()

Upvotes: 1

MostafaR
MostafaR

Reputation: 3695

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

Upvotes: 5

Related Questions