Django得到一个外键 [英] Django get count on a ForeignKey

查看:96
本文介绍了Django得到一个外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获得属于的所有联系人的总计数,但是从名为批量的模型中获取...



这将有助于解释



模型(未显示) / p>

  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)

所以在批量内我想做这样的事情....



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $

但是,由于小组的关系其他方式,我正在努力奋斗。



任何选项?

解决方案

  return self.group.contact_set.count()


I need to get the total count of all contacts that belong to a group, but from within the model called batch....

This will help explain

models (not shown in full)

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)

So within batch I want to do something like this....

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

But as group has the relationship the other way around I'm struggling.

Any options?

解决方案

return self.group.contact_set.count()

这篇关于Django得到一个外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆