Search code examples
djangodjango-taggit

post_save doesn't list tags


Idea is to use a post_save signal to do things if an object has certain tags, but the tags are not being listed

@receiver(post_save, sender=List)
def list_saved(sender, instance, created, **kwargs):
    if created:
        for tag in instance.tags.all():
            print(tag.name)

This never lists any tags, it's an empty query set.
Yet if I then open the shell and do:

>>> l = List.objects.filter(pk=1).get()
>>> for tag in l.tags.all():
>>>   print(tag.name)

It works fine.

Why are the tags not available in the post_save?

Tags are added to list as such:

class List(models.Model):
    tags = TaggableManager()

Solution

  • I assume tags is a ManyToManyField at the heart of it. If that's the case, then when you create a List instance it won't have any tags set. You'll need to connect to the m2m_changed signal to determine the changes in the tags collection.