views:

40

answers:

1

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)
+4  A: 

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.

PiotrLegnica