Reputation: 3118
If I have 2 interlinked models:
class Person(models.Model)
name = models.CharField()
class Project(models.Model):
person = models.ForeignKey(Person)
title = models.CharField()
I frequently find myself trying to find the number of Projects associated with each Person:
person = Person.objects.get(id=1)
no_projects = Project.objects.filter(person=person).count()
Is there a way of adding this as a custom field to the Person model, such that I may just call person.no_projects
?
Upvotes: 1
Views: 499
Reputation: 599470
In fact, that functionality is (almost) built-in. Instead of querying Projects, you can just do person.project_set.count()
to get that person's count of projects (and .all()
to get the actual list).
Upvotes: 4
Reputation: 4609
You can use the property() to generate the dynamical field.
class Project(models.Model):
person = models.ForeignKey(Person)
title = models.CharField()
def _get_no_projects(self):
return Projects.objects.filter(person=self).count()
no_projects = property(_get_no_projects)
But the dynamical fields can not be used in querying, because the they don't really store data into the database.
FYI: http://www.b-list.org/weblog/2006/aug/18/django-tips-using-properties-models-and-managers/
Upvotes: 1
Reputation: 32244
This can be done by adding a property to the Person class.
class Person(models.Model)
name = models.CharField()
@property
def no_projects(self):
return Project.objects.filter(person=self).count()
This can be called now like this
person = Person.objects.get(id=1)
person.no_projects
Upvotes: 4