3

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?

4

1 回答 1

4

django-taggit 完全符合您的要求,但在您的情况下 sampletag != Sample_tag 因此创建了另一个 Tag 实例。

>>> i.tags.all()
[]
>>> i.tags.add("test")
>>> i.tags.all()
[<Tag: test>]
>>> i.tags.add("test")
>>> i.tags.all()
[<Tag: test>]
>>> 
于 2014-11-18T11:38:26.617 回答