【问题标题】:Django get count on a ForeignKeyDjango 依靠 ForeignKey
【发布时间】:2013-03-22 16:04:28
【问题描述】:

我需要从名为 batch 的模型中获取属于 的所有 联系人 的总数... .

这将有助于解释

模型(未完整显示)

class Batch(models.Model):
    #FK
    group = models.ForeignKey(Group, null=True, blank=True)


class Group(models.Model):
    name = models.CharField(max_length=60)



class Contact(models.Model):

    first_name = models.CharField(max_length=60)
    group = models.ForeignKey(Group)

所以在批处理中我想做这样的事情......

 def get_contact_count(self):
        return len(self.group.contacts)

但是作为一个群体,我的关系正好相反。

有什么选择吗?

【问题讨论】:

    标签: django django-models


    【解决方案1】:
    return self.group.contact_set.count()
    

    【讨论】:

    • +1 即将发布相同的内容,您还可以在 Contact 模型中的 foreignKey 上设置一个 related_name 属性来代替“contact_set”。
    【解决方案2】:
    def get_contact_count(self):
        return Contact.objects.filter(group=self.group).count()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-12
      • 2011-12-11
      • 2021-06-09
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多