问题
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