Django-Taggit通过简单的ManyToManyField()实现标记提供了什么好处? [英] What benefit does Django-Taggit provide over a simple ManyToManyField() implementation of tagging?
本文介绍了Django-Taggit通过简单的ManyToManyField()实现标记提供了什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Django-Taggit文档中的示例:
class Food(models.Model):
#...这里的字段
标签= TaggableManager()
那么你可以像API这样使用API ::
>>> apple = Food.objects.create(name =apple)
>>> apple.tags.add(red,green,delicious)
>>> apple.tags.all()
[<标签:红色><标签:绿色><标签:美味>]
>>> apple.tags.remove(green)
>>>> apple.tags.all()
[< Tag:red>< Tag:delicious>]
>>> Food.objects.filter(tags__name__in = [red])
[<食物:苹果><食物:樱桃>]
解决方案
真正的优势在于找不到对象的标签,而不是标签的对象。具体来说,如果您有多种类型的可以标记的对象,请想象:
class Food(models.Model):
tags = models.ManyToManyField(Tag)
class Wine(models.Model):
tags = models.ManyToManyField(Tag)
现在找到我标记为紫色的对象的所有实例。 Taggit使它变得更容易。
The API according to the documentation seems achievable with a simple ManyToManyField...what am I missing?
Sample from Django-Taggit documentation:
class Food(models.Model):
# ... fields here
tags = TaggableManager()
Then you can use the API like so::
>>> apple = Food.objects.create(name="apple")
>>> apple.tags.add("red", "green", "delicious")
>>> apple.tags.all()
[<Tag: red>, <Tag: green>, <Tag: delicious>]
>>> apple.tags.remove("green")
>>> apple.tags.all()
[<Tag: red>, <Tag: delicious>]
>>> Food.objects.filter(tags__name__in=["red"])
[<Food: apple>, <Food: cherry>]
解决方案
The real advantage is not in finding the tags of an object, but rather the objects for a tag. And specifically, if you have multiple types of objects that can be tagged, imagine:
class Food(models.Model):
tags = models.ManyToManyField(Tag)
class Wine(models.Model):
tags = models.ManyToManyField(Tag)
Now find me all the instances of objects tagged "purple". Taggit makes it a lot easier to do so.
这篇关于Django-Taggit通过简单的ManyToManyField()实现标记提供了什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文