Django get count on a ForeignKey

雨燕双飞 提交于 2020-01-16 18:37:15

问题


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?


回答1:


return self.group.contact_set.count()



回答2:


def get_contact_count(self):
    return Contact.objects.filter(group=self.group).count()


来源:https://stackoverflow.com/questions/15574821/django-get-count-on-a-foreignkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!