简体   繁体   中英

Django-taggit adding new tags to an object?

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 (ie "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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM