TAGS :Viewed: 6 - Published at: a few seconds ago

[ Using a method in a model to count objects filtered by the primary key ]

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)

Answer 1


When you create a ForeignKey, Django creates a backref on referenced model for you, so you could just do:

def popularity(self):
    return self.playlistitem_set.count()

See http://docs.djangoproject.com/en/1.1/topics/db/queries/#backwards-related-objects.