Django-taggit adding new tags to an object?

1.8k views Asked by At

My models.py

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

How to add tags to an object. If I do:

 x = X.objects.get(pk = 123)
 x.tags.add( "sample_tag" )

It adds the tag twice, if the tag with same name (i.e "sample_tag" in the above in the case) has been previously created. Now when I retrieve tags :

>>> x.tags.all()
>>> [<Tag: sampletag>, <Tag: Sample_tag>]

How to do solve this problem. I want to add a new tag only if its not created before, and if created just refer the new object to that tag?

1

There are 1 answers

0
kviktor On

django-taggit does exactly what you want, but in your case sampletag != Sample_tag, so another Tag instance is created.

>>> i.tags.all()
[]
>>> i.tags.add("test")
>>> i.tags.all()
[<Tag: test>]
>>> i.tags.add("test")
>>> i.tags.all()
[<Tag: test>]
>>>