0

I want to count tags . I have Post model and tags model and post model has manytomany field to tags. When I want to add new post meanwhile I add tags for post , it has to increase tag count number.

My Post and Tags model:

class Post(models.Model):

    tags = models.ManyToManyField(Tag,blank=True,null=True,verbose_name=_('tags'))

    def save(self)
       super(Post, self).save()
       for i in self.tags.all():
       i.save() 

class Tag(models.Model):

    name=models.CharField(max_length=30,verbose_name=_('name'))
    count = models.IntegerField(blank=True,null=True,default=0)
    slug = models.SlugField(blank=True,null=True)

    def save(self):
       self.slug = slugify(self.name.upper())
       self.count = Post.objects.filter(tags__name=self.name).count()
       super(Tag, self).save()

When I added new post , I look up the tag model and see count number does not change but when I press the save button in Tags Admin then I see the real count. But I want to see real count when I look up the tag admin without pressing the save button in tag.

Also I want that when I edit the post it should not increase the tags count again.

aysekucuk
  • 461
  • 5
  • 16
  • You seem to be dealing with [this](http://stackoverflow.com/questions/1925383/issue-with-manytomany-relationships-not-updating-inmediatly-after-save) issue. – Jesse the Game Nov 05 '12 at 14:49

2 Answers2

0

I would use m2m_changed signal for this problem.

jpic
  • 32,891
  • 5
  • 112
  • 113
0

You could do the following:

class Post(models.Model):

    tags = models.ManyToManyField(Tag,blank=True,null=True,verbose_name=_('tags'))

    def save(self)
        super(Post, self).save()
        for tag in self.tags :
            tag.count = tag.post_set.count()
            tag.save()

OR, instead of saving the count value into a field, just do the lookup when needed:

tag.post_set.count()

you could add a function to Tag to get this on the easy:

def count(self) :
    return self.post_set.count()
Francis Yaconiello
  • 10,829
  • 2
  • 35
  • 54