0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Django-taggit

Posted at
# タグ名称で取得
>>> blog_1.tags.names()
<QuerySet ['Python', 'Django']>

# slugで取得
>>> blog_1.tags.slugs()
<QuerySet ['Python', 'Django']>

# オブジェクトで取得
>>> blog_1.tags.all()
<QuerySet [<Tag: Python>, <Tag: Django>]>

#追加
>>> blog_1.tags.add('programming')
<QuerySet ['Python', 'Django', 'programming']>

#削除
>>> blog_1.tags.remove('programming')
<QuerySet ['Python', 'Django']>

#全部削除
>>> blog_1.tags.clear()
<QuerySet []>

# タグでfilter
>>> Blog.objects.filter(tags__name__in=["Python", "Django"])
<QuerySet [<Blog: 1つ目の記事>, <Blog: 1つ目の記事>]>

# タグでfilter(重複なし)
>>> Blog.objects.filter(tags__name__in=["Python", "Django"]).distinct()
<QuerySet [<Blog: 1つ目の記事>]>

# 関連記事(共通のタグが多い順でオブジェクトを取得)
>>> blog_1.tags.similar_objects()
[<Blog: 3つ目の記事>, <Blog: 2つ目の記事>]

# タグモデル取得
>>> Tag.objects.all()
<QuerySet [<Tag: Python>, <Tag: Django>, <Tag: programming>]>

# 「Pythonタグ」と紐づいたBlog一覧
>>> tag = Tag.objects.get(name="Python")
>>> Blog.objects.filter(tags=tag)
<QuerySet [<Blog: 1つ目の記事>, <Blog: 2つ目の記事>, <Blog: 3つ目の記事>]>

紐ずいたblgoの多い順
>>> Tag.objects.all().annotate(c=Count('taggit_taggeditem_items')).order_by('-c')
<QuerySet [<Tag: programming>, <Tag: Python>, <Tag: Django>]>
0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?