I wanted to use a method as part of my model to count all the occurrences of the object in another table that references it as a foreign key.
Will the below work?
class Tile(models.Model):
#...
def popularity(self):
return PlaylistItem.objects.filter(tile__exact=self.id).count()
And the relevant information from the playlistitem model:
class PlaylistItem(models.Model):
#...
tile = models.ForeignKey(Tile)
When you create a
ForeignKey, Django creates a backref on referenced model for you, so you could just do:See http://docs.djangoproject.com/en/1.1/topics/db/queries/#backwards-related-objects.