0

With the following code I want to return the count this works...

def contact_count(self):
    return len(self.contacts)

However, if the len is 0 is returns blank and I want it to be 0.

So I have tried

def contact_count(self):
    if len(self.contacts) == 0:
       return 0
    else:
      return len(self.contacts)

Is there a better way I should be handling this?

UPDATE:

So to update my question as asked this is how contacts is defined...

models.py

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

    def contact_count(self):
        return len(self.contacts)

class Contacts(models.Model):
    first_name = models.CharField(max_length=60)
    last_name = models.CharField(max_length=60)
    #FK
    groups = models.ManyToManyField(Groups, related_name='contacts')

As you can see if comes from the related_name

4
  • 1
    how is contacts defined? Commented Mar 13, 2013 at 21:24
  • return 0 if not self.contact else len(self.contacts) although it's only a matter of style really as what you have works Commented Mar 13, 2013 at 21:25
  • 1
    what do you mean len(self.contacts) returns blank? Maybe you get error page because you're trying to len(None) which is exception? Commented Mar 13, 2013 at 21:25
  • see update above to show where contacts comes from. Commented Mar 13, 2013 at 21:31

1 Answer 1

3

You should use self.contacts.count().

See Django docs on many to many relations for more details.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.