# タグ名称で取得
>>> 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>]>
More than 3 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme