Helmi
Helmi

Reputation: 539

Count the usage of a many to many field in Django for string representation

My Topic model has a ManyToMany Relation to the Post modell. As part of it's string representation I wanted to have its usage count but I'm unsure how to query that.

class Topic(models.Model):
    posts = models.ManyToManyField(Post)
    name = models.CharField(max_length=100, blank=False)

    def __str__(self):
        return self.name

so in addition to self.name I'd like to return the count how often that very Topic is used on Posts.

Upvotes: 1

Views: 178

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

Try to use self.posts.count():

def __str__(self):
    return '{}, posts count: {}'.format(self.name, self.posts.count())

Upvotes: 1

Related Questions