与简单的 ManyToManyField() 标记实现相比,Django-Taggit 有什么好处?

发布于 2024-10-01 23:08:28 字数 664 浏览 2 评论 0原文

根据文档的 API 似乎可以通过简单的 ManyToManyField 来实现......我错过了什么?

Django-Taggit 文档中的示例:

class Food(models.Model):
    # ... fields here

    tags = TaggableManager()

然后您可以像这样使用 API::

>>> 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 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>]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清秋悲枫 2024-10-08 23:08:28

真正的优势不在于找到对象的标签,而在于找到标签的对象。具体来说,如果您有多种类型的可以标记的对象,想象一下:

class Food(models.Model):
   tags = models.ManyToManyField(Tag)

class Wine(models.Model):
   tags = models.ManyToManyField(Tag)

现在找到标记为“紫色”的对象的所有实例。 Taggit 让这一切变得更加容易。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文