4
4

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 5 years have passed since last update.

【Django】django-taggitで日本語のタグを検索するとき

Posted at

#django-taggitで日本語のタグを検索する方法

日本語(が含まれる)のタグを検索する際は、一文字ずつ分割される仕様?となっていますが、
下記のように指定したいタグが一つの場合でもリストとして渡すことで期待した動作を得られます。

from django.shortcuts import get_object_or_404, render, redirect
from django.views.generic.list import ListView
from hoge.models import Article, Blog

###上手く動作する例

my.view
class Tag(ListView,):
    template_name = 'hogehtml'
    paginate_by = 20

    def get(self, request, *args, **kwargs):
        articles = Article.objects.filter(
            tags__name__in=kwargs['tag_name']).distinct().order_by('published_at').reverse()
        tag_list = kwargs['tag_name'].split()
        self.object_list = articles
        context = self.get_context_data(
            articles=self.object_list, tag=tag_list)
        return self.render_to_response(context)

###参考)うまく動作しない例

my.view
class Tag(ListView,):
    template_name = 'hogehtml'
    paginate_by = 20

    def get(self, request, *args, **kwargs):
        articles = Article.objects.filter(
            tags__name__in=kwargs['tag_name']).distinct().order_by('published_at').reverse()
        self.object_list = articles
        context = self.get_context_data(
            articles=self.object_list, tag=kwargs['tag_name'])
        return self.render_to_response(context)

「日本語」で文字列のまま使おうとすると「日」「本」「語」の3つで検索されます。使いづれえ…

###雑記
Djangoさん扱いやすくて便利だと思いきや色々なところでつまづきまくってます。
まあこれはそもそもDjango本体ではないのですが。。。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?