【问题标题】:Using a method in a model to count objects filtered by the primary key使用模型中的方法对按主键过滤的对象进行计数
【发布时间】:2010-02-05 14:36:03
【问题描述】:

我想在我的模型中使用一种方法来计算对象在另一个表中的所有出现次数,该表将其作为外键引用。

下面的方法有用吗?

class Tile(models.Model):
    #...
    def popularity(self):
        return PlaylistItem.objects.filter(tile__exact=self.id).count()

以及来自playlistitem模型的相关信息:

class PlaylistItem(models.Model):
    #...
    tile = models.ForeignKey(Tile)

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    当你创建一个ForeignKey 时,Django 会为你创建一个引用模型的反向引用,所以你可以这样做:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      相关资源
      最近更新 更多