Dynamically adding many to many relationships in the save method in Django
<p>My Content model has a many-to-many relationship to the Tag model. When I save a Content object, I want to add the relationships dynamically. Im doing this the following way.</p>

<pre><code># models.py   

def tag_content(content_id):
    obj = Content.objects.get(pk=content_id)
    print obj # Checking
    obj.tags = [1, 2, 3] # Adding the relationships using the Tag IDs

class Tag(models.Model):
    name = models.CharField(max_length=255)

class Content(models.Model):
    title = models.CharField(max_length=255)
    is_tagged = models.BooleanField(default=False)
    tags = models.ManyToManyField(Tag, blank=True)

    def save(self, *args, **kwargs):
        super(Content, self).save(*args, **kwargs)
        if not self.is_tagged:
            tag_content(self.pk) # calling the tagging method
</code></pre>

<p>In other words, when a Content object is saved, its tags field is related to 3 different Tag object models. Just to let you know, I do have the Tags with pks = 1, 2, and 3 in database.</p>

<p>However, this simply doesn't work. The save method calls the tag_content method, since the print obj statement works. However, the many-to-many field is not set and remains empty. The funny thing is, If I run the following commands in shell, the tags field is set perfectly. </p>

<pre><code># python manage.py shell
from myapp.models import *
obj = Content.objects.get(pk=1)
tag_content(obj.pk)
</code></pre>

<p>So how come the shell version works, but the other one doesn't? Any help is appreciated.</p>